from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
import requests, json, jwt, base64, re, pymysql, hashlib, math
from django.utils import timezone
from django.conf import settings
from django.db.models import Q, F
from rest_framework.viewsets import ModelViewSet
from rest_framework import filters
from django_filters.rest_framework import DjangoFilterBackend
from django.db import transaction
from random import randint, shuffle
import random
from django.shortcuts import render
from django_redis import get_redis_connection
from django.db.models.expressions import RawSQL
from django.db.models import Count, Sum, Max, Min, Avg

from customers.serializers import *
from equity_mall.utils.WXBizDataCrypt import WXBizDataCrypt
from customers.utils import AlipayOpen, pay_transactions_jsapi, pay_transactions_native, favor_distributed_coupons, favor_query_coupons, favor_meituan_coupons, favor_query_coupons_sichun, favor_distributed_coupons_sichun
from equity_mall.utils.pages import MyPage
from customers.filters import *
from equity_mall.utils.utils import redis_baidu_token, chack_identify, mmpaymkttransfers, redis_scheme_token, mmpaymkttransfers_xh
from equity_mall.utils.qiniu_storage import pic_upload
from equity_mall.celery import celery_app
from managers.tasks import capture_payeeFullName
from users.models import User
from customers.tasks import *


class UserLoginView(APIView):

    permission_classes = ()

    def post(self, request):
        # mobile = '13510535265'
        # user = CustomerUser.objects.get(mobile=mobile)
        # dic = {
        #     'exp': timezone.now() + datetime.timedelta(days=30),
        #     'iat': timezone.now(),
        #     'iss': 'customer',
        #     'data': {
        #         'mobile_phone': mobile,
        #         'id': user.id,
        #         'username': user.username,
        #         'realname': user.realname,
        #         'is_new': 1
        #     },
        # }
        # jwt_token = jwt.encode(dic, settings.CUSTOMER_SECRET_KEY, algorithm='HS256')
        # return Response({'username': user.username, 'user_id': user.id, 'token': jwt_token, 'mobile': user.mobile}, status=status.HTTP_200_OK)
        HTTP_USER_AGENT = self.request.environ['HTTP_USER_AGENT']
        if 'WeChat' in HTTP_USER_AGENT or 'MicroMessenger' in HTTP_USER_AGENT:
            code = self.request.data.get('code', None)
            encryptedData = self.request.data.get('encryptedData', None)
            iv = self.request.data.get('iv', None)
            is_new = self.request.data.get('is_new', '')
            if not all([code, encryptedData, iv]):
                return Response({'error': '缺少必传参数!'}, status=status.HTTP_400_BAD_REQUEST)
            if str(is_new) == '1':
                appid = settings.CUSTOMER_APP_ID_NEW
                secret = settings.CUSTOMER_APP_SECRET_NEW
            elif str(is_new) == '2':
                appid = settings.CUSTOMER_APP_ID_WYH
                secret = settings.CUSTOMER_APP_SECRET_WYH
            else:
                appid = settings.CUSTOMER_APP_ID
                secret = settings.CUSTOMER_APP_SECRET
            url = f'https://api.weixin.qq.com/sns/jscode2session?appid={appid}&secret={secret}&js_code={code}&grant_type=authorization_code'
            response = requests.get(url)
            data_dict = json.loads(response.content)
            if 'errcode' in data_dict:
                return Response({'error': str(data_dict['errcode']) + '错误,请联系管理员!'}, status=status.HTTP_400_BAD_REQUEST)
            session_key = data_dict['session_key']
            openid = data_dict['openid']
            pc = WXBizDataCrypt(appid, session_key)
            try:
                mobile = pc.decrypt(encryptedData, iv)['phoneNumber']
            except Exception as e:
                logging.error(e)
                print(e)
                return Response({'error': '获取手机号错误,请重新登录!'}, status=status.HTTP_400_BAD_REQUEST)
            user, create = CustomerUser.objects.get_or_create(mobile=mobile, defaults={'mobile': mobile, 'create_time': datetime.datetime.now()})
            if create:
                AliDiscountCouponInfo.objects.filter(Q(mobile=mobile, customer_user__isnull=True)).update(customer_user_id=user.id)
            if str(is_new) == '1':
                user.new_openid = openid
                user.save()
            elif str(is_new) == '2':
                user.wyh_openid = openid
                user.save()
            else:
                user.openid = openid
                user.save()
            speedloanuserinfo = SpeedLoanUserInfo.objects.filter(customeruser_id=user.id)
            if not speedloanuserinfo:
                realname = self.request.data.get('realname', None)
                age = str(self.request.data.get('age', None))
                province = self.request.data.get('province', None)
                city = self.request.data.get('city', None)
                district = self.request.data.get('district', None)
                industry_id = self.request.data.get('industry_id', None)
                address = self.request.data.get('address', None)
                business_limit = self.request.data.get('business_limit', None)
                is_house = str(self.request.data.get('is_house', None))
                business_no = self.request.data.get('business_no', None)
                identify = self.request.data.get('identify', None)
                if realname:
                    if not all([realname, age, province, city, district, industry_id, address, business_limit, is_house]):
                        return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
                    try:
                        industry = SpeedLoanIndustry.objects.get(id=industry_id)
                    except:
                        return Response({'error': '无效行业参数'}, status=status.HTTP_400_BAD_REQUEST)
                    if not age.isdigit():
                        return Response({'error': '年龄参数须为整数型'}, status=status.HTTP_400_BAD_REQUEST)
                    if not 18<=int(age)<=98:
                        return Response({'error': '年龄允许范围为18-98'}, status=status.HTTP_400_BAD_REQUEST)
                    if is_house not in ['0', '1']:
                        return Response({'error': '是否有固定房产参数有误'}, status=status.HTTP_400_BAD_REQUEST)
                    speed_data = {}
                    speed_data['realname'] = realname
                    speed_data['age'] = age
                    speed_data['province'] = province
                    speed_data['city'] = city
                    speed_data['district'] = district
                    speed_data['industry_id'] = industry_id
                    speed_data['address'] = address
                    speed_data['business_limit'] = business_limit
                    speed_data['is_house'] = is_house
                    speed_data['customeruser_id'] = user.id
                    speed_data['mobile'] = mobile
                    speed_data['create_time'] = datetime.datetime.now()
                    if identify:
                        sendsms = SpeedSendSMS.objects.filter(identify=identify).first()
                        if sendsms:
                            sendsms.is_send = 2
                            sendsms.save()
                            speed_data['business_no'] = sendsms.business_no
                    SpeedLoanUserInfo.objects.get_or_create(defaults=speed_data, customeruser_id=user.id)
        else:
            encryptedData = self.request.data.get('encryptedData', None)
            code = self.request.data.get('code', None)
            is_new = self.request.data.get('is_new', None)
            if not all([encryptedData, code]):
                return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
            alipay_obj = AlipayOpen()
            if not is_new:
                result = json.loads(alipay_obj.systemoauthtoken(code))
                if 'user_id' not in result:
                    return Response({'error': '获取用户信息失败,请重新操作'}, status=status.HTTP_400_BAD_REQUEST)
                user_id = result['user_id']
                result = json.loads(alipay_obj.getPhoneNumber(encryptedData))
                if result['code'] != '10000':
                    return Response({'error': result['subMsg']}, status=status.HTTP_400_BAD_REQUEST)
            else:
                result = json.loads(alipay_obj.new_systemoauthtoken(code))
                if 'user_id' not in result:
                    return Response({'error': '获取用户信息失败,请重新操作'}, status=status.HTTP_400_BAD_REQUEST)
                user_id = result['user_id']
                result = json.loads(alipay_obj.new_getPhoneNumber(encryptedData))
                if result['code'] != '10000':
                    return Response({'error': result['subMsg']}, status=status.HTTP_400_BAD_REQUEST)
            try:
                mobile = result['mobile']
            except:
                return Response({'error': '获取手机号失败,请重新操作'}, status=status.HTTP_400_BAD_REQUEST)
            customer_data = {}
            customer_data['mobile'] = mobile
            user = CustomerUser.objects.filter(mobile=mobile).first()
            if user:
                if not user.ali_user_id:
                    user.ali_user_id = user_id
                    user.save()
            else:
                customer_data['ali_user_id'] = user_id
                # customer_data['is_auth'] = 2
                customer_data['create_time'] = datetime.datetime.now()
                user, create = CustomerUser.objects.get_or_create(mobile=mobile, defaults=customer_data)
                AliDiscountCouponInfo.objects.filter(mobile=mobile, customer_user__isnull=True).update(customer_user_id=user.id)
                # AliDiscountCouponInfo.objects.filter(user_id=user_id, customer_user__isnull=True).update(customer_user_id=user.id)
        # mobile = '13510535265'
        # user = CustomerUser.objects.get(mobile=mobile)
        dic = {
            'exp': timezone.now() + datetime.timedelta(days=30),
            'iat': timezone.now(),
            'iss': 'customer',
            'data': {
                'mobile_phone': mobile,
                'id': user.id,
                'username': user.username,
                'realname': user.realname,
                'is_new': is_new
            },
        }
        jwt_token = jwt.encode(dic, settings.CUSTOMER_SECRET_KEY, algorithm='HS256')
        return Response({'username': user.username, 'user_id': user.id, 'token': jwt_token, 'mobile': user.mobile}, status=status.HTTP_200_OK)


class UserModelViewSet(ModelViewSet):

    def info(self, request):
        user = self.request.iser
        data = UserInfoModelSerializer(user).data
        data['coupon_count'] = user.alidiscountcouponinfo_set.all().exclude(status__in=[13]).count()
        data['order_total_count'] = user.orderinfo_set.all().count()
        data['order_wait_count'] = user.orderinfo_set.filter(state=1).count()
        data['order_achieve_count'] = user.orderinfo_set.filter(state=12).count()
        data['couponbag_count'] = CustomizeActivityFlipCARDS.objects.filter(user_id=user.id, customizeactivity__activity_type=11).count()
        return Response(data, status=status.HTTP_200_OK)

    def synchronous_info(self, request):
        user = self.request.iser
        nickname = self.request.data.get('nickname', None)
        avatar = self.request.data.get('avatar', None)
        if nickname:
            user.username = nickname
        if avatar:
            user.avatar = avatar
        user.save()
        return Response({'success': '操作成功'}, status=status.HTTP_200_OK)

    def upload_img(self, request):
        '''上传图片'''
        user = self.request.iser
        img = self.request.FILES.get('img', None)
        keyword = self.request.data.get('keyword', None)
        if not all([img, keyword]):
            return Response({'error': '缺少必传参数!'}, status=status.HTTP_400_BAD_REQUEST)
        if img.size > 2097152:
            return Response({'error': '照片不得超过2M,请重新上传!'}, status=status.HTTP_400_BAD_REQUEST)
        img_str = img.read()
        img.seek(0)
        try:
            img_id = f'youhuiquanyi/customer/identification_copy/{random_str(32)}.png'
            mid_img = pic_upload(img_str, key=img_id)
        except Exception as e:
            logger.error(e)
            return Response({'error': '图片上传失败,请重新上传!'}, status=status.HTTP_400_BAD_REQUEST)
        data = {}
        data['img_id'] = img_id
        if keyword == 'id_card_copy':
            request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard"
            id_card_copy = base64.b64encode(img_str)
            redis_conn = get_redis_connection("baidu")
            access_token = redis_conn.get('access_token')
            if access_token is None:
                access_token = redis_baidu_token()
            else:
                access_token = access_token.decode()
            params = {"id_card_side": "front", "image": id_card_copy}
            url = request_url + "?access_token=" + access_token
            headers = {'content-type': 'application/x-www-form-urlencoded'}
            try:
                response = requests.post(url, data=params, headers=headers)
                data_dict = response.json()
                data['id_card_name'] = data_dict['words_result']['姓名']['words']
                data['id_card_number'] = data_dict['words_result']['公民身份号码']['words']
                user.identification_front_copy = img_id
                user.save()
            except Exception as e:
                data['id_card_name'] = ''
                data['id_card_number'] = ''
                logger.error(e)
                pass
        elif keyword == 'id_card_national':
            request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard"
            id_card_national = base64.b64encode(img_str)
            redis_conn = get_redis_connection("baidu")
            access_token = redis_conn.get('access_token')
            if access_token is None:
                access_token = redis_baidu_token()
            else:
                access_token = access_token.decode()
            params = {"id_card_side": "back", "image": id_card_national}
            url = request_url + "?access_token=" + access_token
            headers = {'content-type': 'application/x-www-form-urlencoded'}
            try:
                response = requests.post(url, data=params, headers=headers)
                data_dict = response.json()
                card_period_end = data_dict['words_result']['失效日期']['words']
                card_period_begin = data_dict['words_result']['签发日期']['words']
                data['card_period_end'] = (card_period_end[0:4] + '-' + card_period_end[4:6] + '-' + card_period_end[6:8]) if card_period_end != '长期' else card_period_end
                data['card_period_begin'] = card_period_begin[0:4] + '-' + card_period_begin[4:6] + '-' + card_period_begin[6:8]
            except Exception as e:
                logger.error(e)
                pass
        elif keyword == 'bankcard':
            dic = {
                '邮储银行': '邮政储蓄银行',
                '工商银行': '工商银行',
                '民生银行': '民生银行',
                '交通银行': '交通银行',
                '中国银行': '中国银行',
                '招商银行': '招商银行',
                '中信银行': '中信银行',
                '浦东发展': '浦发银行',
                '兴业银行': '兴业银行',
                '光大信用卡中心': '光大银行',
                '广发': '广发银行',
                '平安银行': '平安银行',
                '北京银行': '北京银行',
                '华夏银行总行': '华夏银行',
                '农业银行': '农业银行',
                '建设银行': '建设银行',
                '宁波银行（贷）': '宁波银行',
            }
            lis = ['邮政储蓄银行', '工商银行', '民生银行', '交通银行',
                   '中国银行', '招商银行', '中信银行', '浦发银行',
                   '兴业银行', '光大银行', '广发银行', '平安银行', '北京银行',
                   '华夏银行', '农业银行', '建设银行', '宁波银行']
            request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/bankcard"
            img = base64.b64encode(img_str)
            redis_conn = get_redis_connection("baidu")
            access_token = redis_conn.get('access_token')
            if access_token is None:
                access_token = redis_baidu_token()
            else:
                access_token = access_token.decode()
            params = {"image": img}
            url = request_url + "?access_token=" + access_token
            headers = {'content-type': 'application/x-www-form-urlencoded'}
            response = requests.post(url, data=params, headers=headers)
            data_dict = response.json()
            try:
                data['bank_card_number'] = data_dict['result']['bank_card_number'].replace(' ', "")
                try:
                    data['bank_name'] = dic[data_dict['result']['bank_name']]
                except:
                    data['bank_name'] = '其他银行'
            except:
                return Response({"error": '您上传的银行卡无法识别，请手动添加！'}, status=status.HTTP_400_BAD_REQUEST)
        elif keyword == 'license_copy':
            request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/business_license"
            img = base64.b64encode(img_str)
            redis_conn = get_redis_connection("baidu")
            access_token = redis_conn.get('access_token')
            if access_token is None:
                access_token = redis_baidu_token()
            else:
                access_token = access_token.decode()
            params = {"image": img}
            url = request_url + "?access_token=" + access_token
            headers = {'content-type': 'application/x-www-form-urlencoded'}
            try:
                response = requests.post(url, data=params, headers=headers)
                data_dict = response.json()
                data['capital'] = data_dict['words_result']['注册资本']['words']
                data['license_number'] = data_dict['words_result']['社会信用代码']['words']
                data['merchant_name'] = data_dict['words_result']['单位名称']['words']
                data['legal_person'] = data_dict['words_result']['法人']['words']
                data['cert_number'] = data_dict['words_result']['证件编号']['words']
                data['subject_type'] = data_dict['words_result']['组成形式']['words']
                data['date'] = data_dict['words_result']['成立日期']['words']
                data['company_address'] = data_dict['words_result']['地址']['words']
                data['qualification_type'] = data_dict['words_result']['经营范围']['words']
                data['type'] = data_dict['words_result']['类型']['words']
                data['effective'] = data_dict['words_result']['有效期']['words']
            except Exception as e:
                logger.error(e)
                pass
        return Response(data=data, status=status.HTTP_200_OK)

    def auth(self, request):
        user = self.request.iser
        id_card_name = self.request.data.get('id_card_name', None)
        id_card_number = self.request.data.get('id_card_number', None)
        identification_type = self.request.data.get('identification_type', '1')
        if not all([id_card_name, id_card_number]):
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        if str(identification_type) == '1':
            if not bool(re.match(r'^\d{17}[\dX]$', id_card_number)):
                return Response({'error': '身份证（中国大陆居民）格式有误'}, status=status.HTTP_400_BAD_REQUEST)
        elif str(identification_type) == '2':
            if not bool(re.match(r'^[A-Za-z0-9-]{4,15}$', id_card_number)):
                return Response({'error': '护照（境外人士）格式有误'}, status=status.HTTP_400_BAD_REQUEST)
        elif str(identification_type) == '3':
            if not bool(re.match(r'^[Hh][A-Za-z0-9]{8,10}$', id_card_number)):
                return Response({'error': '中国香港居民--来往内地通行证格式有误'}, status=status.HTTP_400_BAD_REQUEST)
        elif str(identification_type) == '4':
            if not bool(re.match(r'^[Mm][A-Za-z0-9]{8,10}$', id_card_number)):
                return Response({'error': '中国澳门居民--来往内地通行证格式有误'}, status=status.HTTP_400_BAD_REQUEST)
        elif str(identification_type) == '5':
            if not bool(re.match(r'^\d{8,10}$', id_card_number)):
                return Response({'error': '中国台湾居民--来往大陆通行证格式有误'}, status=status.HTTP_400_BAD_REQUEST)
        elif str(identification_type) == '6':
            if not bool(re.match(r'^\d{15}$', id_card_number)):
                return Response({'error': '外国人居留证格式有误'}, status=status.HTTP_400_BAD_REQUEST)
        elif str(identification_type) == '7':
            if not bool(re.match(r'^[A-Za-z]\d{6}\([0-9A]\)$', id_card_number)):
                return Response({'error': '港澳居民证格式有误'}, status=status.HTTP_400_BAD_REQUEST)
        elif str(identification_type) == '8':
            if not bool(re.match(r'^\d{8,10}$', id_card_number)):
                return Response({'error': '台湾居民证格式有误'}, status=status.HTTP_400_BAD_REQUEST)
        else:
            return Response({'error': '联系人证件类型有误'}, status=status.HTTP_400_BAD_REQUEST)
        # if len(id_card_number) != 18:
        #     return Response({'error': '身份证格式有误'}, status=status.HTTP_400_BAD_REQUEST)
        # identify_result = chack_identify(id_card_number)
        # if 'error' in identify_result:
        #     return Response({'error': identify_result['error']}, status=status.HTTP_400_BAD_REQUEST)
        # if not identify_result['success']:
        #     return Response({'error': '身份证号码有误，请输入正确的号码'}, status=status.HTTP_400_BAD_REQUEST)
        user.realname = id_card_name
        user.idcode = id_card_number
        user.identification_type = identification_type
        user.is_auth = 2
        user.save()
        return Response({'success': '提交认证成功'}, status=status.HTTP_200_OK)


class CustomerUserAddressModelViewSet(ModelViewSet):

    def get_queryset(self):
        user = self.request.iser
        queryset = CustomerUserAddress.objects.filter(customeruser_id=user.id, is_deleted=0).order_by('-create_time')
        return queryset

    def create(self, request, *args, **kwargs):
        user = self.request.iser
        place = self.request.data.get('address', None)
        province = self.request.data.get('prov', None)
        city = self.request.data.get('city', None)
        district = self.request.data.get('area', None)
        mobile = self.request.data.get('mobilePhone', None)
        receiver = self.request.data.get('fullname', None)
        is_default = self.request.data.get('is_default', None)
        if not all([place, city, district, mobile, receiver, province]):
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return Response({"error": "您输入的手机号格式不正确"}, status=status.HTTP_400_BAD_REQUEST)
        address_data = {}
        address_data['place'] = place
        address_data['province'] = province
        address_data['city'] = city
        address_data['district'] = district
        address_data['mobile'] = mobile
        address_data['receiver'] = receiver
        address_data['customeruser_id'] = user.id
        address_data['create_time'] = datetime.datetime.now()
        address, create = CustomerUserAddress.objects.get_or_create(
            place=place,
            province=province,
            city=city,
            district=district,
            mobile=mobile,
            receiver=receiver,
            customeruser_id=user.id,
            defaults=address_data
        )
        if not create and address.is_deleted == 1:
            address.is_deleted = 0
            address.save()
        if is_default:
            CustomerUserAddress.objects.filter(customeruser_id=user.id).update(is_default=0)
            address.is_default = 1
            address.save()
        return Response({'success': '添加地址成功'}, status=status.HTTP_200_OK)

    def update(self, request, *args, **kwargs):
        instance = self.get_object()
        user = self.request.iser
        place = self.request.data.get('address', None)
        province = self.request.data.get('prov', None)
        city = self.request.data.get('city', None)
        district = self.request.data.get('area', None)
        mobile = self.request.data.get('mobilePhone', None)
        receiver = self.request.data.get('fullname', None)
        is_default = self.request.data.get('is_default', None)
        if not all([place, city, district, mobile, receiver, province]):
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return Response({"error": "您输入的手机号格式不正确"}, status=status.HTTP_400_BAD_REQUEST)
        address_data = {}
        address_data['place'] = place
        address_data['province'] = province
        address_data['city'] = city
        address_data['district'] = district
        address_data['mobile'] = mobile
        address_data['receiver'] = receiver
        address_data['customeruser_id'] = user.id
        address_data['create_time'] = instance.create_time
        address, create = CustomerUserAddress.objects.get_or_create(
            place=place,
            province=province,
            city=city,
            district=district,
            mobile=mobile,
            receiver=receiver,
            customeruser_id=user.id,
            defaults=address_data
        )
        if instance.id == address.id:
            if is_default:
                CustomerUserAddress.objects.filter(customeruser_id=user.id).update(is_default=0)
                address.is_default = 1
                address.save()
        else:
            instance.is_delete = 1
            instance.save()
            if is_default:
                CustomerUserAddress.objects.filter(customeruser_id=user.id).update(is_default=0)
                address.is_default = 1
            address.is_deleted = 0
            address.save()
        return Response({'success': '操作成功'}, status=status.HTTP_200_OK)


class MerchantModelViewSet(ModelViewSet):

    pagination_class = MyPage
    filter_backends = (filters.SearchFilter, DjangoFilterBackend)
    search_fields = ('name', )
    filter_class = MerchantFilter

    def get_queryset(self):
        longitude = self.request.query_params.get('longitude', None)
        latitude = self.request.query_params.get('latitude', None)
        if not all([longitude, latitude]):
            queryset = Merchant.objects.filter(is_online=2)
        else:
            gcd_formula = "6371 * acos(least(greatest(cos(radians(%s)) * cos(radians(latitude)) * cos(radians(longitude) - radians(%s)) + sin(radians(%s)) * sin(radians(latitude)) , -1), 1))"
            sql = RawSQL(gcd_formula, (latitude, longitude, latitude))
            queryset = Merchant.objects.filter(is_online=2).annotate(distance=sql).order_by(F('distance').asc(nulls_last=True))
        return queryset

    def get_serializer_class(self):
        if self.action == 'list':
            return MerchantListModelSerializer
        else:
            return MerchantRetrieveModelSerializer

    def get_serializer_context(self):
        longitude = self.request.query_params.get('longitude', None)
        latitude = self.request.query_params.get('latitude', None)
        return {'longitude': longitude, 'latitude': latitude}

    def navigation_bar(self, request):
        queryset = GoodsCategory.objects.filter(id=1)
        classList = []
        data = []
        for query in queryset:
            data.append(GoodsCategoryModelSerializer(query).data)
            if len(data) == 10:
                classList.append(data)
                data = []
        if data:
            classList.append(data)
        return Response({'classList': classList}, status=status.HTTP_200_OK)


class AliDiscountCouponModelViewSet(ModelViewSet):

    pagination_class = MyPage

    def get_queryset(self):
        # user = self.request.iser
        merchant_id = self.request.query_params.get('merchant_id', None)
        # if user:
        #     try:
        #         conn = pymysql.connect(host=settings.DATABASES['default']['HOST'],
        #                                port=settings.DATABASES['default']['PORT'],
        #                                database=settings.DATABASES['default']['NAME'],
        #                                user=settings.DATABASES['default']['USER'],
        #                                password=settings.DATABASES['default']['PASSWORD'])
        #         cursor = conn.cursor(cursor=pymysql.cursors.SSDictCursor)
        #         sql = f'SELECT count(a.customer_user_id),a.alidiscountcoupon_id,a.max_number_by_user FROM (SELECT tb_ali_discount_coupon_info.customer_user_id,tb_ali_discount_coupon_info.alidiscountcoupon_id,tb_ali_discount_coupon.max_number_by_user FROM tb_ali_discount_coupon_info LEFT JOIN tb_ali_discount_coupon ON tb_ali_discount_coupon_info.alidiscountcoupon_id=tb_ali_discount_coupon.id)AS a WHERE a.customer_user_id={user.id} GROUP BY alidiscountcoupon_id HAVING COUNT(a.customer_user_id)=<a.max_number_by_user;'
        #         cursor.execute(sql)
        #         rows = cursor.fetchall()
        #         cursor.close()
        #         conn.close()
        #         l1 = []
        #         for row in rows:
        #             l1.append(row['alidiscountcoupon_id'])
        #         queryset = AliDiscountCoupon.objects.filter(id__in=l1, coupon_status=1)
        #     except:
        #         queryset = AliDiscountCoupon.objects.filter(coupon_status=1)
        # else:
            # queryset = AliDiscountCoupon.objects.filter()
        queryset = AliDiscountCoupon.objects.filter(coupon_status=1)
        if self.action == 'limit_alidiscountcoupon':
            queryset = queryset.filter(coupon_way=3, publish_end_time__gte=datetime.datetime.now()).order_by('start_enable_time')
            return queryset
        elif self.action == 'list':
            queryset = queryset.filter(coupon_way=2)
            if merchant_id:
                queryset = queryset.filter(alidiscountcouponmerchant__merchant_id=merchant_id)
            else:
                queryset = queryset.filter(is_union=1)
        else:
            queryset = queryset.filter(coupon_way__in=[2, 3])
        return queryset.order_by('-id')

    def get_serializer_class(self):
        return AliDiscountCouponModelSerializer

    def get_serializer_context(self):
        user = self.request.iser
        return {'user': user}

    def retrieve(self, request, *args, **kwargs):
        activity = self.get_object()
        user = self.request.iser
        alidiscountcoupon_level = AliDiscountCouponLevel.objects.filter(activity_id=activity.id).first()
        out_biz_no = f'100004{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
        try:
            channelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
            if channelcommonvoucher.distributed_limit_by_time == 1:
                week = str(datetime.datetime.now().weekday())
                enable_time = datetime.datetime.now().strftime('1970-01-01 %H:%M:%S')
                alidiscountcoupondstributedlimit = AliDiscountCouponDistributedLimit.objects.filter(ali_discount_coupon_common_voucher_id=channelcommonvoucher.id, weeks__contains=week, start_enable_time__lte=enable_time, end_enable_time__gte=enable_time)
                if not alidiscountcoupondstributedlimit:
                    return Response({'error': '没到活动派发时间'}, status=status.HTTP_400_BAD_REQUEST)
        except:
            pass
        if activity.is_white:
            is_white = AliDiscountCouponWhiteTable.objects.filter(mobile=user.mobile, alidiscountcoupon_id=activity.id)
            if not is_white:
                return Response({'error': '您没有该优惠券领取权限，请联系客户经理参与活动。'}, status=status.HTTP_400_BAD_REQUEST)
        if activity.max_number_by_day:
            begin_time = datetime.datetime.now().strftime('%Y-%m-%d 00:00:00')
            end_time = datetime.datetime.now().strftime('%Y-%m-%d 23:59:59')
            max_no = AliDiscountCouponInfo.objects.filter(alidiscountcoupon_id=activity.id, gmt_create__gte=begin_time,
                                                          gmt_create__lte=end_time).count()
            if max_no >= activity.max_number_by_day:
                return Response({'error': '今天的优惠券已领取完毕，请明天0点继续参与，感谢您对本活动的支持！'}, status=status.HTTP_400_BAD_REQUEST)
        if activity.max_number_by_user:
            max_no = AliDiscountCouponInfo.objects.filter(alidiscountcoupon_id=activity.id,
                                                          customer_user_id=user.id).count()
            if max_no >= activity.max_number_by_user:
                return Response({'error': '用户参与活动次数已达上限，感谢您对本活动的支持！'}, status=status.HTTP_400_BAD_REQUEST)
        if alidiscountcoupon_level.remain_number <= 0:
            return Response({'error': '活动已达到派发上限'}, status=status.HTTP_400_BAD_REQUEST)
        query = AliDiscountCouponInfo.objects.filter(customer_user_id=user.id, alidiscountcoupon_id=activity.id)
        if 1 in query.values_list('status', flat=True):
            return Response({'error': '活动设定领1张使用1张规则'}, status=status.HTTP_400_BAD_REQUEST)
        elif activity.max_number_by_user <= query.count():
            return Response({'error': '活动已达到领取上限'}, status=status.HTTP_400_BAD_REQUEST)
        alidiscountcoupon_level_id = alidiscountcoupon_level.id
        activity_id = activity.id
        if activity.coupon_channel == 1:
            if not user.ali_user_id:
                return Response({'error': '用户尚未关联支付宝,请使用支付宝【赋有】小程序授权登录'}, status=status.HTTP_400_BAD_REQUEST)
            alipay_obj = AlipayOpen()
            user_id = user.ali_user_id
            template_id = activity.template_id
            result = json.loads(alipay_obj.vouchersend(user_id, template_id, out_biz_no))
            if result['code'] != '10000':
                logger.error(str(result))
                try:
                    return Response({'error': result['sub_msg']}, status=status.HTTP_400_BAD_REQUEST)
                except:
                    return Response({'error': '领取失败,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
            voucher_id = result['voucher_id']
            if activity.platform_id == 1:
                result = json.loads(alipay_obj.voucherquery(voucher_id))
                data = {
                    'alidiscountcoupon_id': activity.id,
                    'voucher_id': voucher_id,
                    'user_id': user_id,
                    'template_id': result['template_id'],
                    'gmt_active': result['gmt_active'],
                    'gmt_expired': result['gmt_expired'],
                    'total_amount': result['total_amount'],
                    'gmt_create': result['gmt_create'],
                    'available_amount': result['available_amount'],
                    'name': result['name'],
                    'out_biz_no': out_biz_no,
                    'customer_user_id': user.id,
                    'gmt_distributed': datetime.datetime.now(),
                    'alidiscountcoupon_level_id': alidiscountcoupon_level.id,
                    'level_id': alidiscountcoupon_level.level_id,
                    'mobile': user.mobile,
                    'coupon_channel': activity.coupon_channel
                }
            else:
                gmt_create = datetime.datetime.now()
                alidiscountcouponchannelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
                if alidiscountcouponchannelcommonvoucher.usetime_type == 2:
                    gmt_expired = alidiscountcouponchannelcommonvoucher.end_fixed_time
                    gmt_active = alidiscountcouponchannelcommonvoucher.start_fixed_time
                elif alidiscountcouponchannelcommonvoucher.usetime_type == 3:
                    gmt_expired = gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)
                    gmt_active = gmt_create
                else:
                    gmt_active = (gmt_create + datetime.timedelta(days=1)).strftime("%Y-%m-%d 00:00:00")
                    gmt_expired = (gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)).strftime("%Y-%m-%d 23:59:59")
                data = {
                    'alidiscountcoupon_id': activity.id,
                    'voucher_id': voucher_id,
                    'user_id': user_id,
                    'template_id': activity.template_id,
                    'gmt_active': gmt_active,
                    'gmt_expired': gmt_expired,
                    'total_amount': activity.amount,
                    'gmt_create': gmt_create,
                    'available_amount': activity.amount,
                    'name': activity.activity_name,
                    'out_biz_no': out_biz_no,
                    'customer_user_id': user.id,
                    'gmt_distributed': datetime.datetime.now(),
                    'alidiscountcoupon_level_id': alidiscountcoupon_level.id,
                    'level_id': alidiscountcoupon_level.level_id,
                    'mobile': user.mobile,
                    'coupon_channel': activity.coupon_channel
                }
            voucherinfo, create = AliDiscountCouponInfo.objects.get_or_create(defaults=data, voucher_id=voucher_id)
            while True:
                alidiscountcoupon_level = AliDiscountCouponLevel.objects.get(id=alidiscountcoupon_level_id)
                instance_origin_take_number = alidiscountcoupon_level.take_number
                instance_origin_receive_number = alidiscountcoupon_level.receive_number
                instance_origin_remain_number = alidiscountcoupon_level.remain_number
                instance_origin_p_take_number = alidiscountcoupon_level.p_take_number
                instance_origin_p_receive_number = alidiscountcoupon_level.p_receive_number
                instance_origin_p_remain_number = alidiscountcoupon_level.p_remain_number
                instance_new_take_number = instance_origin_take_number + 1
                instance_new_receive_number = instance_origin_receive_number + 1
                instance_new_remain_number = instance_origin_remain_number - 1
                instance_new_p_take_number = instance_origin_p_take_number + 1
                instance_new_p_receive_number = instance_origin_p_receive_number + 1
                instance_new_p_remain_number = instance_origin_p_remain_number - 1
                result = AliDiscountCouponLevel.objects.filter(id=alidiscountcoupon_level_id, take_number=instance_origin_take_number).update(
                    take_number=instance_new_take_number,
                    receive_number=instance_new_receive_number,
                    remain_number=instance_new_remain_number,
                    p_take_number=instance_new_p_take_number,
                    p_receive_number=instance_new_p_receive_number,
                    p_remain_number=instance_new_p_remain_number
                )
                if result == 0:
                    continue
                break
            while True:
                activity = AliDiscountCoupon.objects.get(id=activity_id)
                activity_origin_send_count = activity.send_count
                activity_origin_remain_number = activity.remain_number
                activity_new_send_count = activity_origin_send_count + 1
                activity_new_remain_number = activity_origin_remain_number - 1
                result = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
                    send_count=activity_new_send_count,
                    remain_number=activity_new_remain_number
                )
                if result == 0:
                    continue
                break
            # alidiscountcoupon_level.take_number += 1
            # alidiscountcoupon_level.receive_number += 1
            # alidiscountcoupon_level.remain_number -= 1
            # alidiscountcoupon_level.p_take_number += 1
            # alidiscountcoupon_level.p_receive_number += 1
            # alidiscountcoupon_level.p_remain_number -= 1
            # alidiscountcoupon_level.save()
            # activity.send_count += 1
            # activity.remain_number -= 1
            # activity.save()
            try:
                relation_set = alidiscountcoupon_level.child_set.all()
                for relation in relation_set:
                    parent = relation.parent
                    parent.p_take_number += 1
                    parent.p_receive_number += 1
                    parent.p_remain_number -= 1
                    parent.save()
            except:
                pass
            if create:
                return Response({'success': '领取成功', 'coupon_id': voucherinfo.id}, status=status.HTTP_200_OK)
            else:
                return Response({'error': '已经领取过了'}, status=status.HTTP_400_BAD_REQUEST)
        elif activity.coupon_channel == 2:
            if user.new_openid:
                appid = settings.CUSTOMER_APP_ID_NEW
                openid = user.new_openid
            elif user.openid:
                appid = settings.CUSTOMER_APP_ID
                openid = user.openid
            else:
                return Response({'error': '用户尚未关联微信,请使用微信【赋有】小程序授权登录'}, status=status.HTTP_400_BAD_REQUEST)
            if activity.platform_id == 13:
                distribute_channel = Channel.objects.get(id=13)
            else:
                distribute_channel = Channel.objects.get(id=9)
            data_json = {
                "stock_id": activity.template_id,
                "out_request_no": out_biz_no,
                "appid": appid,
                "stock_creator_mchid": activity.platform.mchid
            }
            data_dict = favor_distributed_coupons_sichun(data_json, openid, distribute_channel)
            if 'code' in data_dict:
                return Response({'error': data_dict['message']}, status=status.HTTP_400_BAD_REQUEST)
            coupon_id = data_dict['coupon_id']
            voucherinfo = AliDiscountCouponInfo.objects.filter(voucher_id=coupon_id).first()
            if voucherinfo:
                return Response({'error': '已经领取过了'}, status=status.HTTP_400_BAD_REQUEST)
            result = favor_query_coupons_sichun(coupon_id, openid, appid, distribute_channel)
            data = {
                'alidiscountcoupon_id': activity.id,
                'voucher_id': coupon_id,
                'user_id': openid,
                'template_id': result['stock_id'],
                'gmt_active': result['available_begin_time'].replace('T', ' ').replace('+08:00', ''),
                'gmt_expired': result['available_end_time'].replace('T', ' ').replace('+08:00', ''),
                'total_amount': result['normal_coupon_information']['coupon_amount'] / 100,
                'gmt_create': datetime.datetime.now(),
                'available_amount': result['normal_coupon_information']['coupon_amount'] / 100,
                'name': result['coupon_name'],
                'out_biz_no': out_biz_no,
                'customer_user_id': user.id,
                'gmt_distributed': datetime.datetime.now(),
                'alidiscountcoupon_level_id': alidiscountcoupon_level.id,
                'level_id': alidiscountcoupon_level.level_id,
                'mobile': user.mobile,
                'coupon_channel': activity.coupon_channel
            }
            while True:
                alidiscountcoupon_level = AliDiscountCouponLevel.objects.get(id=alidiscountcoupon_level_id)
                instance_origin_take_number = alidiscountcoupon_level.take_number
                instance_origin_receive_number = alidiscountcoupon_level.receive_number
                instance_origin_remain_number = alidiscountcoupon_level.remain_number
                instance_origin_p_take_number = alidiscountcoupon_level.p_take_number
                instance_origin_p_receive_number = alidiscountcoupon_level.p_receive_number
                instance_origin_p_remain_number = alidiscountcoupon_level.p_remain_number
                instance_new_take_number = instance_origin_take_number + 1
                instance_new_receive_number = instance_origin_receive_number + 1
                instance_new_remain_number = instance_origin_remain_number - 1
                instance_new_p_take_number = instance_origin_p_take_number + 1
                instance_new_p_receive_number = instance_origin_p_receive_number + 1
                instance_new_p_remain_number = instance_origin_p_remain_number - 1
                result = AliDiscountCouponLevel.objects.filter(id=alidiscountcoupon_level_id, take_number=instance_origin_take_number).update(
                    take_number=instance_new_take_number,
                    receive_number=instance_new_receive_number,
                    remain_number=instance_new_remain_number,
                    p_take_number=instance_new_p_take_number,
                    p_receive_number=instance_new_p_receive_number,
                    p_remain_number=instance_new_p_remain_number
                )
                if result == 0:
                    continue
                break
            while True:
                activity = AliDiscountCoupon.objects.get(id=activity_id)
                activity_origin_send_count = activity.send_count
                activity_origin_remain_number = activity.remain_number
                activity_new_send_count = activity_origin_send_count + 1
                activity_new_remain_number = activity_origin_remain_number - 1
                result = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
                    send_count=activity_new_send_count,
                    remain_number=activity_new_remain_number
                )
                if result == 0:
                    continue
                break
            # alidiscountcoupon_level.take_number += 1
            # alidiscountcoupon_level.receive_number += 1
            # alidiscountcoupon_level.remain_number -= 1
            # alidiscountcoupon_level.p_take_number += 1
            # alidiscountcoupon_level.p_receive_number += 1
            # alidiscountcoupon_level.p_remain_number -= 1
            # alidiscountcoupon_level.save()
            # activity.send_count += 1
            # activity.remain_number -= 1
            # activity.save()
            try:
                relation_set = alidiscountcoupon_level.child_set.all()
                for relation in relation_set:
                    parent = relation.parent
                    parent.p_take_number += 1
                    parent.p_receive_number += 1
                    parent.p_remain_number -= 1
                    parent.save()
            except:
                pass
            voucherinfo, create = AliDiscountCouponInfo.objects.get_or_create(defaults=data, voucher_id=coupon_id)
            if create:
                return Response({'success': '领取成功', 'coupon_id': voucherinfo.id}, status=status.HTTP_200_OK)
            else:
                return Response({'error': '已经领取过了'}, status=status.HTTP_400_BAD_REQUEST)
        else:
            voucher_id = f'{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}{random_str(14)}'
            user_id = user.ali_user_id
            gmt_create = datetime.datetime.now()
            alidiscountcouponchannelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
            if alidiscountcouponchannelcommonvoucher.usetime_type == 2:
                gmt_expired = alidiscountcouponchannelcommonvoucher.end_fixed_time
                gmt_active = alidiscountcouponchannelcommonvoucher.start_fixed_time
            elif alidiscountcouponchannelcommonvoucher.usetime_type == 3:
                gmt_expired = gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)
                gmt_active = gmt_create
            else:
                gmt_active = (gmt_create + datetime.timedelta(days=1)).strftime("%Y-%m-%d 00:00:00")
                gmt_expired = (gmt_create + datetime.timedelta(
                    days=alidiscountcouponchannelcommonvoucher.invalid_day)).strftime("%Y-%m-%d 23:59:59")
            data = {
                'alidiscountcoupon_id': activity.id,
                'voucher_id': voucher_id,
                'user_id': user_id,
                'template_id': activity.template_id,
                'gmt_active': gmt_active,
                'gmt_expired': gmt_expired,
                'total_amount': activity.amount,
                'gmt_create': gmt_create,
                'available_amount': activity.amount,
                'name': activity.activity_name,
                'out_biz_no': out_biz_no,
                'customer_user_id': user.id,
                'alidiscountcoupon_level_id': alidiscountcoupon_level.id,
                'level_id': alidiscountcoupon_level.level_id,
                'mobile': user.mobile,
                'gmt_distributed': datetime.datetime.now(),
                'coupon_channel': activity.coupon_channel
            }
            while True:
                alidiscountcoupon_level = AliDiscountCouponLevel.objects.get(id=alidiscountcoupon_level_id)
                instance_origin_take_number = alidiscountcoupon_level.take_number
                instance_origin_receive_number = alidiscountcoupon_level.receive_number
                instance_origin_remain_number = alidiscountcoupon_level.remain_number
                instance_origin_p_take_number = alidiscountcoupon_level.p_take_number
                instance_origin_p_receive_number = alidiscountcoupon_level.p_receive_number
                instance_origin_p_remain_number = alidiscountcoupon_level.p_remain_number
                instance_new_take_number = instance_origin_take_number + 1
                instance_new_receive_number = instance_origin_receive_number + 1
                instance_new_remain_number = instance_origin_remain_number - 1
                instance_new_p_take_number = instance_origin_p_take_number + 1
                instance_new_p_receive_number = instance_origin_p_receive_number + 1
                instance_new_p_remain_number = instance_origin_p_remain_number - 1
                result = AliDiscountCouponLevel.objects.filter(id=alidiscountcoupon_level_id, take_number=instance_origin_take_number).update(
                    take_number=instance_new_take_number,
                    receive_number=instance_new_receive_number,
                    remain_number=instance_new_remain_number,
                    p_take_number=instance_new_p_take_number,
                    p_receive_number=instance_new_p_receive_number,
                    p_remain_number=instance_new_p_remain_number
                )
                if result == 0:
                    continue
                break
            while True:
                activity = AliDiscountCoupon.objects.get(id=activity_id)
                activity_origin_send_count = activity.send_count
                activity_origin_remain_number = activity.remain_number
                activity_new_send_count = activity_origin_send_count + 1
                activity_new_remain_number = activity_origin_remain_number - 1
                result = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
                    send_count=activity_new_send_count,
                    remain_number=activity_new_remain_number
                )
                if result == 0:
                    continue
                break
            # alidiscountcoupon_level.take_number += 1
            # alidiscountcoupon_level.receive_number += 1
            # alidiscountcoupon_level.remain_number -= 1
            # alidiscountcoupon_level.p_take_number += 1
            # alidiscountcoupon_level.p_receive_number += 1
            # alidiscountcoupon_level.p_remain_number -= 1
            # alidiscountcoupon_level.save()
            # activity.send_count += 1
            # activity.remain_number -= 1
            # activity.save()
            try:
                relation_set = alidiscountcoupon_level.child_set.all()
                for relation in relation_set:
                    parent = relation.parent
                    parent.p_take_number += 1
                    parent.p_receive_number += 1
                    parent.p_remain_number -= 1
                    parent.save()
            except:
                pass
            voucherinfo, create = AliDiscountCouponInfo.objects.get_or_create(defaults=data, voucher_id=voucher_id)
            if create:
                return Response({'success': '领取成功', 'coupon_id': voucherinfo.id}, status=status.HTTP_200_OK)
            else:
                return Response({'error': '已经领取过了'}, status=status.HTTP_400_BAD_REQUEST)

    def limit_alidiscountcoupon(self, request):
        queryset = self.get_queryset()
        if not queryset:
            return Response([], status=status.HTTP_200_OK)
        user = self.request.iser
        data = AliDiscountCouponLimitModelSerializer(queryset, context={'user': user}, many=True).data
        return Response(data, status=status.HTTP_200_OK)

    def allow_coupon(self, request):
        identify = self.request.query_params.get('identify', None)
        user = self.request.iser
        if not all([identify]):
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            activity = AliDiscountCoupon.objects.get(id=identify)
        except:
            return Response({'error': '无效二维码,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
        data = {}
        data['activity_name'] = activity.activity_name
        if activity.coupon_type == 6:
            data['amount'] = '商品兑换券'
        else:
            data['amount'] = activity.amount
        data['floor_amount'] = activity.floor_amount
        data['publish_end_time'] = activity.publish_end_time.strftime('%Y年%m月%d日 %H:%M:%S')
        if activity.coupon_type in [2, 6, 8]:
            channelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
            if channelcommonvoucher.usetime_type == 2:
                data['usetime_type'] = f'固定时间段{channelcommonvoucher.start_fixed_time.strftime("%Y.%m.%d %H:%M:%S")}-{channelcommonvoucher.end_fixed_time.strftime("%Y.%m.%d %H:%M:%S")}'
            elif channelcommonvoucher.usetime_type == 3:
                data['usetime_type'] = f'领取后立即生效有效时间{channelcommonvoucher.invalid_day}天'
            else:
                data['usetime_type'] = f'领取后次日凌晨生效有效时间{channelcommonvoucher.invalid_day}天'
        else:
            data['usetime_type'] = ''
        data['activity_description'] = activity.activity_description
        if not user:
            a = 1
        else:
            try:
                query = AliDiscountCouponInfo.objects.filter(customer_user_id=user.id, alidiscountcoupon_id=activity.id)
                if 1 in query.values_list('status', flat=True):
                    try:
                        id_list = query.filter(status=1).values_list('id', flat=True)
                        synchronous_wx_coupons_status(list(id_list))
                        query2 = AliDiscountCouponInfo.objects.filter(customer_user_id=user.id, alidiscountcoupon_id=activity.id)
                        if 1 in query2.values_list('status', flat=True):
                            a = 2
                        elif activity.max_number_by_user > query2.count():
                            a = 1
                        else:
                            a = 2
                    except:
                        a = 2
                elif activity.max_number_by_user > query.count():
                    a = 1
                else:
                    a = 2
            except:
                a = 1
        data['state'] = a
        data['is_need_auth'] = activity.is_need_auth
        data['coupon_type'] = activity.coupon_type
        data['coupon_type_str'] = activity.get_coupon_type_display()
        data['is_psbc_card'] = activity.is_psbc_card
        return Response(data, status=status.HTTP_200_OK)

    def allow_coupon_wyh(self, request):
        user = self.request.iser
        identify = self.request.query_params.get('identify', None)
        longitude = self.request.query_params.get('longitude', None)
        latitude = self.request.query_params.get('latitude', None)
        if not all([identify]):
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            activity = AliDiscountCoupon.objects.get(template_id=identify, coupon_way=8)
        except:
            return Response({'error': '无效活动参数,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
        data = {}
        data['activity_name'] = activity.activity_name
        if activity.coupon_type == 6:
            data['amount'] = '商品兑换券'
        else:
            data['amount'] = activity.amount
        data['floor_amount'] = activity.floor_amount
        data['publish_end_time'] = activity.publish_end_time.strftime('%Y年%m月%d日 %H:%M:%S')
        channelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
        if channelcommonvoucher.usetime_type == 2:
            data['usetime_type'] = f'固定时间段{channelcommonvoucher.start_fixed_time.strftime("%Y.%m.%d %H:%M:%S")}-{channelcommonvoucher.end_fixed_time.strftime("%Y.%m.%d %H:%M:%S")}'
        elif channelcommonvoucher.usetime_type == 3:
            data['usetime_type'] = f'领取后立即生效有效时间{channelcommonvoucher.invalid_day}天'
        else:
            data['usetime_type'] = f'领取后次日凌晨生效有效时间{channelcommonvoucher.invalid_day}天'
        if channelcommonvoucher.join_limit_by_user == 1:
            data['join_limit_by_user'] = f'活动期间每个用户可参与{channelcommonvoucher.join_limit_by_user_count}次'
        else:
            data['join_limit_by_user'] = '不限制'
        if channelcommonvoucher.join_limit_by_location == 1:
            if longitude and latitude:
                check_location = AliDiscountCouponJoinLimitLocation.objects.filter(
                    longitude_begin__lte=longitude,
                    longitude_end__gte=longitude,
                    latitude_begin__lte=latitude,
                    latitude_end__gte=latitude,
                    ali_discount_coupon_common_voucher_id=channelcommonvoucher.id
                )
                if check_location:
                    join_limit = 1
                else:
                    join_limit = 0
            else:
                join_limit = 0
        else:
            join_limit = 1

        data['activity_description'] = activity.activity_description
        if datetime.datetime.now() > activity.publish_end_time:
            a = 2
        elif datetime.datetime.now() < activity.publish_start_time:
            a = 3
        else:
            if not user:
                a = 1
            else:
                if channelcommonvoucher.join_limit_by_user == 1:
                    coupon_count = AliDiscountCouponInfo.objects.filter(alidiscountcoupon_id=activity.id, customer_user_id=user.id).count()
                    if coupon_count >= channelcommonvoucher.join_limit_by_user_count:
                        a = 0
                    else:
                        a = 1
                else:
                    a = 1
        if activity.remain_number <= 0:
            a = 4
        data['state'] = a
        data['join_limit'] = join_limit
        data['is_need_auth'] = activity.is_need_auth
        data['coupon_type'] = activity.coupon_type
        data['coupon_type_str'] = activity.get_coupon_type_display()
        data['is_psbc_card'] = activity.is_psbc_card
        return Response(data, status=status.HTTP_200_OK)

    def retrieve_coupon_wyh(self, request):
        user = self.request.iser
        identify = self.request.data.get('identify', None)
        longitude = self.request.data.get('longitude', None)
        latitude = self.request.data.get('latitude', None)
        login_id = self.request.data.get('login_id', None)
        if not all([identify, longitude, longitude, login_id]):
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            activity = AliDiscountCoupon.objects.get(template_id=identify, coupon_way=8)
        except:
            return Response({'error': '无效活动参数,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
        if activity.coupon_status != 1:
            return Response({'error': '活动已结束'}, status=status.HTTP_400_BAD_REQUEST)
        if activity.remain_number <= 0:
            return Response({'error': '活动已达到派发上限'}, status=status.HTTP_400_BAD_REQUEST)
        out_biz_no = f'100004{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
        channelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
        if channelcommonvoucher.distributed_limit_by_time == 1:
            week = str(datetime.datetime.now().weekday())
            enable_time = datetime.datetime.now().strftime('1970-01-01 %H:%M:%S')
            alidiscountcoupondstributedlimit = AliDiscountCouponDistributedLimit.objects.filter(
                ali_discount_coupon_common_voucher_id=channelcommonvoucher.id, weeks__contains=week,
                start_enable_time__lte=enable_time, end_enable_time__gte=enable_time)
            if not alidiscountcoupondstributedlimit:
                return Response({'error': '没到活动派发时间'}, status=status.HTTP_400_BAD_REQUEST)
        if activity.is_white:
            is_white = AliDiscountCouponWhiteTable.objects.filter(mobile=user.mobile, alidiscountcoupon_id=activity.id)
            if not is_white:
                return Response({'error': '您没有该优惠券领取权限，请联系客户经理参与活动。'}, status=status.HTTP_400_BAD_REQUEST)
        if activity.is_check_identity == 1:
            check_manager = User.objects.filter(mobile=user.mobile, is_active=1)
            if check_manager:
                return Response({'error': '该活动暂不允许内部员工领取，如有疑问请咨询客服。'}, status=status.HTTP_400_BAD_REQUEST)
        if activity.max_number_by_day:
            begin_time = datetime.datetime.now().strftime('%Y-%m-%d 00:00:00')
            end_time = datetime.datetime.now().strftime('%Y-%m-%d 23:59:59')
            max_no = AliDiscountCouponInfo.objects.filter(alidiscountcoupon_id=activity.id,
                                                          gmt_create__gte=begin_time,
                                                          gmt_create__lte=end_time).count()
            if max_no >= activity.max_number_by_day:
                return Response({'error': '今天的优惠券已领取完毕，请明天0点继续参与，感谢您对本活动的支持！'}, status=status.HTTP_400_BAD_REQUEST)
        if channelcommonvoucher.join_limit_by_user:
            max_no = AliDiscountCouponInfo.objects.filter(alidiscountcoupon_id=activity.id, customer_user_id=user.id).count()
            if max_no >= channelcommonvoucher.join_limit_by_user_count:
                return Response({'error': '用户参与活动次数已达上限，感谢您对本活动的支持！'}, status=status.HTTP_400_BAD_REQUEST)
        if activity.remain_number <= 0:
            return Response({'error': '活动已达到派发上限'}, status=status.HTTP_400_BAD_REQUEST)
        if user.is_auth != 2 and activity.is_need_auth == 1:
            return Response({'error': '请先完成实名认证'}, status=status.HTTP_400_BAD_REQUEST)
        if channelcommonvoucher.join_limit_by_location == 1:
            check_location = AliDiscountCouponJoinLimitLocation.objects.filter(
                longitude_begin__lte=longitude,
                longitude_end__gte=longitude,
                latitude_begin__lte=latitude,
                latitude_end__gte=latitude,
                ali_discount_coupon_common_voucher_id=channelcommonvoucher.id
            )
            if not check_location:
                return Response({'error': '当前区域不支持参与该活动'}, status=status.HTTP_400_BAD_REQUEST)
        activity_id = activity.id
        while True:
            activity = AliDiscountCoupon.objects.get(id=activity_id)
            activity_origin_send_count = activity.send_count
            activity_origin_remain_number = activity.remain_number
            activity_new_send_count = activity_origin_send_count + 1
            activity_new_remain_number = activity_origin_remain_number - 1
            result = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
                send_count=activity_new_send_count,
                remain_number=activity_new_remain_number
            )
            if result == 0:
                continue
            break
        alipay_obj = AlipayOpen()
        template_id = activity.template_id
        result = json.loads(alipay_obj.vouchersend_login_id(login_id, template_id, out_biz_no))
        if result['code'] != '10000':
            logger.error(str(result))
            while True:
                activity = AliDiscountCoupon.objects.get(id=activity_id)
                activity_origin_send_count = activity.send_count
                activity_origin_remain_number = activity.remain_number
                activity_new_send_count = activity_origin_send_count - 1
                activity_new_remain_number = activity_origin_remain_number + 1
                result1 = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
                    send_count=activity_new_send_count,
                    remain_number=activity_new_remain_number
                )
                if result1 == 0:
                    continue
                break
            try:
                return Response({'error': result['sub_msg']}, status=status.HTTP_400_BAD_REQUEST)
            except:
                return Response({'error': '领取失败,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
        voucher_id = result['voucher_id']
        if activity.platform_id == 1:
            result = json.loads(alipay_obj.voucherquery(voucher_id))
            data = {
                'alidiscountcoupon_id': activity.id,
                'voucher_id': voucher_id,
                'login_id': login_id,
                'template_id': result['template_id'],
                'gmt_active': result['gmt_active'],
                'gmt_expired': result['gmt_expired'],
                'total_amount': result['total_amount'],
                'gmt_create': result['gmt_create'],
                'available_amount': result['available_amount'],
                'name': result['name'],
                'out_biz_no': out_biz_no,
                'customer_user_id': user.id,
                'gmt_distributed': datetime.datetime.now(),
                'mobile': user.mobile,
                'coupon_channel': activity.coupon_channel
            }
        else:
            gmt_create = datetime.datetime.now()
            alidiscountcouponchannelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
            if alidiscountcouponchannelcommonvoucher.usetime_type == 2:
                gmt_expired = alidiscountcouponchannelcommonvoucher.end_fixed_time
                gmt_active = alidiscountcouponchannelcommonvoucher.start_fixed_time
            elif alidiscountcouponchannelcommonvoucher.usetime_type == 3:
                gmt_expired = gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)
                gmt_active = gmt_create
            else:
                gmt_active = (gmt_create + datetime.timedelta(days=1)).strftime("%Y-%m-%d 00:00:00")
                gmt_expired = (gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)).strftime("%Y-%m-%d 23:59:59")
            data = {
                'alidiscountcoupon_id': activity.id,
                'voucher_id': voucher_id,
                'login_id': login_id,
                'template_id': activity.template_id,
                'gmt_active': gmt_active,
                'gmt_expired': gmt_expired,
                'total_amount': activity.amount,
                'gmt_create': gmt_create,
                'available_amount': activity.amount,
                'name': activity.activity_name,
                'out_biz_no': out_biz_no,
                'customer_user_id': user.id,
                'gmt_distributed': gmt_create,
                'mobile': user.mobile,
                'coupon_channel': activity.coupon_channel
            }
        voucherinfo, create = AliDiscountCouponInfo.objects.get_or_create(defaults=data, voucher_id=voucher_id)
        if create:
            return Response({'success': '领取成功', 'coupon_id': voucherinfo.id}, status=status.HTTP_200_OK)
        else:
            return Response({'error': '已经领取过了'}, status=status.HTTP_400_BAD_REQUEST)

    def merchant_activity(self, request):
        user = self.request.iser
        alidiscountcoupon = AliDiscountCoupon.objects.get(id=18387)
        alidiscountcouponinfo = AliDiscountCouponInfo.objects.filter(alidiscountcoupon_id=alidiscountcoupon.id, customer_user_id=user.id).first()
        if alidiscountcouponinfo:
            return Response({'success': '领取成功', 'activity_data': AliDiscountCouponInfoListModelSerializer(alidiscountcouponinfo).data}, status=status.HTTP_200_OK)
        if alidiscountcoupon.coupon_status in [1, 4]:
            now_date = datetime.datetime.now()
            if alidiscountcoupon.publish_end_time < now_date:
                alidiscountcoupon.coupon_status = 2
                alidiscountcoupon.save()
        if alidiscountcoupon.remain_number <= 0:
            return Response({'error': '活动优惠名额已抢光'}, status=status.HTTP_400_BAD_REQUEST)
        if alidiscountcoupon.coupon_status in [2, 4]:
            return Response({'error': '活动已结束'}, status=status.HTTP_400_BAD_REQUEST)
        if alidiscountcoupon.coupon_status == 3:
            return Response({'error': '活动未开始'}, status=status.HTTP_400_BAD_REQUEST)
        check_merchant = Merchant.objects.filter(managermobile=user.mobile, level__prov_id=7330).first()
        if not check_merchant:
            return Response({'error': '您不是特邀商户'}, status=status.HTTP_400_BAD_REQUEST)
        alidiscountcouponinfo = AliDiscountCouponInfo.objects.filter(alidiscountcoupon_id=alidiscountcoupon.id, customer_user_id=user.id).first()
        if alidiscountcouponinfo:
            return Response({'success': '领取成功', 'activity_data': AliDiscountCouponInfoListModelSerializer(alidiscountcouponinfo).data}, status=status.HTTP_200_OK)
        else:
            while True:
                activity = AliDiscountCoupon.objects.get(id=18387)
                activity_origin_send_count = activity.send_count
                activity_origin_remain_number = activity.remain_number
                activity_new_send_count = activity_origin_send_count + 1
                activity_new_remain_number = activity_origin_remain_number - 1
                if activity_new_remain_number < 0:
                    return Response({'error': '活动已结束'}, status=status.HTTP_400_BAD_REQUEST)
                result = AliDiscountCoupon.objects.filter(id=18387, send_count=activity_origin_send_count).update(
                    send_count=activity_new_send_count,
                    remain_number=activity_new_remain_number
                )
                if result == 0:
                    continue
                break
            voucher_id = f'{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}{random_str(14)}'
            out_biz_no = f'100004{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
            user_id = user.ali_user_id
            gmt_create = datetime.datetime.now()
            alidiscountcouponchannelcommonvoucher = alidiscountcoupon.alidiscountcouponchannelcommonvoucher
            if alidiscountcouponchannelcommonvoucher.usetime_type == 2:
                gmt_expired = alidiscountcouponchannelcommonvoucher.end_fixed_time
                gmt_active = alidiscountcouponchannelcommonvoucher.start_fixed_time
            elif alidiscountcouponchannelcommonvoucher.usetime_type == 3:
                gmt_expired = gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)
                gmt_active = gmt_create
            else:
                gmt_active = (gmt_create + datetime.timedelta(days=1)).strftime("%Y-%m-%d 00:00:00")
                gmt_expired = (gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)).strftime("%Y-%m-%d 23:59:59")
            data = {
                'alidiscountcoupon_id': alidiscountcoupon.id,
                'voucher_id': voucher_id,
                'user_id': user_id,
                'template_id': alidiscountcoupon.template_id,
                'gmt_active': gmt_active,
                'gmt_expired': gmt_expired,
                'total_amount': alidiscountcoupon.amount,
                'gmt_create': gmt_create,
                'available_amount': alidiscountcoupon.amount,
                'name': alidiscountcoupon.activity_name,
                'out_biz_no': out_biz_no,
                'customer_user_id': user.id,
                'gmt_distributed': gmt_create,
                'level_id': check_merchant.level_id,
                'mobile': user.mobile,
                'coupon_channel': alidiscountcoupon.coupon_channel
            }
            voucherinfo, create = AliDiscountCouponInfo.objects.get_or_create(defaults=data, out_biz_no=out_biz_no)
            if create:
                return Response({'success': '领取成功', 'activity_data': AliDiscountCouponInfoListModelSerializer(voucherinfo).data}, status=status.HTTP_200_OK)
            else:
                return Response({'success': '领取成功', 'activity_data': AliDiscountCouponInfoListModelSerializer(voucherinfo).data}, status=status.HTTP_200_OK)


class ActivityDataModelViewSet(ModelViewSet):

    pagination_class = MyPage
    filter_backends = (filters.SearchFilter, DjangoFilterBackend)
    filter_class = ActivityDataFilter

    def get_serializer_class(self):
        if self.action == 'list':
            return ActivityDataListModelSerializer
        else:
            return ActivityDataRetrieveModelSerializer

    def get_queryset(self):
        user = self.request.iser
        queryset = ActivityData.objects.filter(customer_user_id=user.id).order_by('-create_time')
        try:
            if '_mutable' in self.request.data.__dict__:
                self.request.data.__dict__['_mutable'] = True
        except:
            pass
        self.request.data['use_count'] = str(queryset.filter(state__in=[2,3]).count())
        self.request.data['not_use_count'] = str(queryset.exclude(state__in=[2,3]).count())
        return queryset

    def allow_point(self, request):
        identify = self.request.query_params.get('identify', None)
        if not all([identify]):
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            activity_data = ActivityData.objects.get(identify=identify)
        except:
            return Response({'error': '无效二维码,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
        activity = activity_data.activity
        data = {}
        data['activity_name'] = activity.name
        point = str(int(activity_data.point))
        if len(point) >= 3:
            point = f'{point[:-2]},{point[-2:]}'
        data['point'] = point
        data['amount'] = activity_data.point / Decimal('100')
        data['available_end_time'] = activity.available_end_time.strftime('%Y年%m月%d日 %H:%M:%S')
        data['state'] = activity_data.state
        data['is_need_auth'] = 1
        data['activity_description'] = activity.activity_description
        return Response(data, status=status.HTTP_200_OK)

    def receive_point(self, request):
        user = self.request.iser
        identify = self.request.data.get('identify', None)
        if not all([identify]):
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            activity_data = ActivityData.objects.get(identify=identify)
        except:
            return Response({'error': '无效二维码,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
        if activity_data.state == 2:
            return Response({'error': '该二维码已经被领取'}, status=status.HTTP_400_BAD_REQUEST)
        if activity_data.state in [4, 5]:
            return Response({'error': '该二维码已过期,请客户经理重新生成'}, status=status.HTTP_400_BAD_REQUEST)
        if activity_data.state != 1:
            return Response({'error': '该二维码已过期,请客户经理重新生成'}, status=status.HTTP_400_BAD_REQUEST)
        if user.is_auth != 2:
            return Response({'error': '请先完成实名认证'}, status=status.HTTP_400_BAD_REQUEST)
        date_now = datetime.datetime.now()
        in_pointrecord_data = {}
        in_pointrecord_data['customer_user_id'] = user.id
        in_pointrecord_data['create_time'] = date_now
        in_pointrecord_data['operate_type'] = 1
        in_pointrecord_data['business_type'] = 1
        in_pointrecord_data['point'] = activity_data.point
        in_pointrecord_data['point_balance'] = activity_data.point + user.point
        in_pointrecord_data['activity_data_id'] = activity_data.id
        in_pointrecord_data['remain_point'] = activity_data.point
        PointRecord.objects.create(**in_pointrecord_data)
        user.point += activity_data.point
        user.save()
        activity_data.state = 2
        activity_data.received_time = date_now
        activity_data.customer_user_id = user.id
        activity_data.save()
        try:
            activity_level_record = activity_data.activitylevelrecord_set.all().update(customer_user_id=user.id)
        except:
            pass
        return Response({'success': '领取成功'}, status=status.HTTP_200_OK)


class PointRecordModelViewSet(ModelViewSet):

    serializer_class = PointRecordModelSerializer
    pagination_class = MyPage

    def get_queryset(self):
        user = self.request.iser
        queryset = PointRecord.objects.filter(customer_user_id=user.id).order_by('-id')
        return queryset


class AliDiscountCouponInfoModelViewSet(ModelViewSet):

    pagination_class = MyPage
    filter_backends = (filters.SearchFilter, DjangoFilterBackend)
    filter_class = AliDiscountCouponInfoFilter

    def get_queryset(self):
        user = self.request.iser
        queryset = AliDiscountCouponInfo.objects.filter(customer_user_id=user.id).exclude(status__in=[13]).order_by('-id')
        return queryset

    def get_serializer_class(self):
        if self.action == 'list':
            return AliDiscountCouponInfoListModelSerializer
        else:
            return AliDiscountCouponInfoRetrieveModelSerializer

    def allow_couponinfo(self, request):
        # user = self.request.iser
        identify = self.request.query_params.get('identify', None)
        if not all([identify]):
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        if len(identify) == 32:
            try:
                qrcode = AliDiscountCouponQRCode.objects.get(identify=identify)
            except:
                return Response({'error': '无效二维码,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
            activity = qrcode.alidiscountcoupon_level.activity
            data = {}
            data['activity_name'] = activity.activity_name
            if activity.coupon_type == 6:
                data['amount'] = '商品兑换券'
            else:
                data['amount'] = activity.amount
            data['floor_amount'] = activity.floor_amount
            data['publish_end_time'] = activity.publish_end_time.strftime('%Y年%m月%d日 %H:%M:%S')
            if activity.coupon_type in [2, 6, 8]:
                channelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
                if channelcommonvoucher.usetime_type == 2:
                    data['usetime_type'] = f'固定时间段{channelcommonvoucher.start_fixed_time.strftime("%Y.%m.%d %H:%M:%S")}-{channelcommonvoucher.end_fixed_time.strftime("%Y.%m.%d %H:%M:%S")}'
                elif channelcommonvoucher.usetime_type == 3:
                    data['usetime_type'] = f'领取后立即生效有效时间{channelcommonvoucher.invalid_day}天'
                else:
                    data['usetime_type'] = f'领取后次日凌晨生效有效时间{channelcommonvoucher.invalid_day}天'
            else:
                data['usetime_type'] = ''
            data['activity_description'] = activity.activity_description
            data['qrcode_state'] = qrcode.qrcode_state
            data['is_need_auth'] = activity.is_need_auth
            data['coupon_type'] = activity.coupon_type
            data['coupon_type_str'] = activity.get_coupon_type_display()
            data['coupon_channel'] = activity.coupon_channel
            data['is_psbc_card'] = activity.is_psbc_card
            data['is_login_id'] = activity.is_login_id
            data['join_limit_by_location'] = 2
            data['is_instructions'] = 1
            return Response(data, status=status.HTTP_200_OK)
        elif len(identify) == 48:
            try:
                alidiscountcouponmanagerqrcode = AliDiscountCouponManagerQRCode.objects.get(identify=identify)
            except:
                return Response({'error': '无效二维码,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
            activity = alidiscountcouponmanagerqrcode.alidiscountcoupon
            data = {}
            data['activity_name'] = activity.activity_name
            if activity.coupon_type == 6:
                data['amount'] = '商品兑换券'
            else:
                data['amount'] = activity.amount
            data['floor_amount'] = activity.floor_amount
            data['publish_end_time'] = activity.publish_end_time.strftime('%Y年%m月%d日 %H:%M:%S')
            if activity.coupon_type in [2, 6, 8]:
                channelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
                if channelcommonvoucher.usetime_type == 2:
                    data['usetime_type'] = f'固定时间段{channelcommonvoucher.start_fixed_time.strftime("%Y.%m.%d %H:%M:%S")}-{channelcommonvoucher.end_fixed_time.strftime("%Y.%m.%d %H:%M:%S")}'
                elif channelcommonvoucher.usetime_type == 3:
                    data['usetime_type'] = f'领取后立即生效有效时间{channelcommonvoucher.invalid_day}天'
                else:
                    data['usetime_type'] = f'领取后次日凌晨生效有效时间{channelcommonvoucher.invalid_day}天'
            else:
                data['usetime_type'] = ''
            data['activity_description'] = activity.activity_description
            data['qrcode_state'] = 1
            data['is_need_auth'] = activity.is_need_auth
            data['coupon_type'] = activity.coupon_type
            data['coupon_type_str'] = activity.get_coupon_type_display()
            data['coupon_channel'] = activity.coupon_channel
            data['is_psbc_card'] = activity.is_psbc_card
            data['is_login_id'] = activity.is_login_id
            data['join_limit_by_location'] = 2
            data['is_instructions'] = 1
            return Response(data, status=status.HTTP_200_OK)
        elif len(identify) == 64:
            try:
                alidiscountcoupon_level = AliDiscountCouponLevel.objects.get(identify=identify)
            except:
                return Response({'error': '无效二维码,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
            activity = alidiscountcoupon_level.activity
            data = {}
            data['activity_name'] = activity.activity_name
            if activity.coupon_type == 6:
                data['amount'] = '商品兑换券'
            else:
                data['amount'] = activity.amount
            data['floor_amount'] = activity.floor_amount
            data['publish_end_time'] = activity.publish_end_time.strftime('%Y年%m月%d日 %H:%M:%S')
            if activity.coupon_type in [2, 6, 8, 11]:
                channelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
                if channelcommonvoucher.usetime_type == 2:
                    data['usetime_type'] = f'固定时间段{channelcommonvoucher.start_fixed_time.strftime("%Y.%m.%d %H:%M:%S")}-{channelcommonvoucher.end_fixed_time.strftime("%Y.%m.%d %H:%M:%S")}'
                elif channelcommonvoucher.usetime_type == 3:
                    data['usetime_type'] = f'领取后立即生效有效时间{channelcommonvoucher.invalid_day}天'
                else:
                    data['usetime_type'] = f'领取后次日凌晨生效有效时间{channelcommonvoucher.invalid_day}天'
                join_limit_by_location = channelcommonvoucher.join_limit_by_location
            else:
                data['usetime_type'] = ''
                join_limit_by_location = 2
            data['activity_description'] = activity.activity_description
            data['qrcode_state'] = 1
            data['is_need_auth'] = activity.is_need_auth
            data['coupon_type'] = activity.coupon_type
            data['coupon_type_str'] = activity.get_coupon_type_display()
            data['coupon_channel'] = activity.coupon_channel
            data['is_psbc_card'] = activity.is_psbc_card
            data['is_login_id'] = activity.is_login_id
            data['join_limit_by_location'] = join_limit_by_location
            if activity.coupon_type == 11:
                data['is_instructions'] = 0
            else:
                data['is_instructions'] = 1
            return Response(data, status=status.HTTP_200_OK)
        else:
            try:
                activity = AliDiscountCoupon.objects.get(id=identify)
            except:
                return Response({'error': '无效活动id,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
            data = {}
            data['activity_name'] = activity.activity_name
            if activity.coupon_type == 6:
                data['amount'] = '商品兑换券'
            else:
                data['amount'] = activity.amount
            data['floor_amount'] = activity.floor_amount
            data['publish_end_time'] = activity.publish_end_time.strftime('%Y年%m月%d日 %H:%M:%S')
            if activity.coupon_type in [2, 6, 8]:
                channelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
                if channelcommonvoucher.usetime_type == 2:
                    data['usetime_type'] = f'固定时间段{channelcommonvoucher.start_fixed_time.strftime("%Y.%m.%d %H:%M:%S")}-{channelcommonvoucher.end_fixed_time.strftime("%Y.%m.%d %H:%M:%S")}'
                elif channelcommonvoucher.usetime_type == 3:
                    data['usetime_type'] = f'领取后立即生效有效时间{channelcommonvoucher.invalid_day}天'
                else:
                    data['usetime_type'] = f'领取后次日凌晨生效有效时间{channelcommonvoucher.invalid_day}天'
            else:
                data['usetime_type'] = ''
            data['activity_description'] = activity.activity_description
            data['qrcode_state'] = 1
            data['is_need_auth'] = activity.is_need_auth
            data['coupon_type'] = activity.coupon_type
            data['coupon_type_str'] = activity.get_coupon_type_display()
            data['coupon_channel'] = activity.coupon_channel
            data['is_psbc_card'] = activity.is_psbc_card
            data['is_login_id'] = activity.is_login_id
            data['join_limit_by_location'] = 2
            data['is_instructions'] = 1
            return Response(data, status=status.HTTP_200_OK)

    def receive_couponinfo(self, request):
        user = self.request.iser
        identify = self.request.data.get('identify', None)
        login_id = self.request.data.get('login_id', None)
        longitude = self.request.data.get('longitude', None)
        latitude = self.request.data.get('latitude', None)
        if not all([identify]):
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        if len(identify) == 32:
            try:
                qrcode = AliDiscountCouponQRCode.objects.get(identify=identify)
            except:
                return Response({'error': '无效二维码,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
            if qrcode.qrcode_state == 2:
                return Response({'error': '该二维码已经被领取'}, status=status.HTTP_400_BAD_REQUEST)
            alidiscountcoupon_level = qrcode.alidiscountcoupon_level
            out_biz_no = qrcode.out_biz_no
            activity = alidiscountcoupon_level.activity
            try:
                channelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
                if channelcommonvoucher.distributed_limit_by_time == 1:
                    week = str(datetime.datetime.now().weekday())
                    enable_time = datetime.datetime.now().strftime('1970-01-01 %H:%M:%S')
                    alidiscountcoupondstributedlimit = AliDiscountCouponDistributedLimit.objects.filter(ali_discount_coupon_common_voucher_id=channelcommonvoucher.id, weeks__contains=week, start_enable_time__lte=enable_time, end_enable_time__gte=enable_time)
                    if not alidiscountcoupondstributedlimit:
                        return Response({'error': '没到活动派发时间'}, status=status.HTTP_400_BAD_REQUEST)
            except:
                pass
            if activity.coupon_status != 1:
                return Response({'error': '活动已结束。'}, status=status.HTTP_400_BAD_REQUEST)
            if activity.is_check_identity == 1:
                check_manager = User.objects.filter(mobile=user.mobile, is_active=1)
                if check_manager:
                    return Response({'error': '该活动暂不允许内部员工领取，如有疑问请咨询客服。', 'status': ''}, status=status.HTTP_400_BAD_REQUEST)
            if activity.is_white:
                is_white = AliDiscountCouponWhiteTable.objects.filter(mobile=user.mobile, alidiscountcoupon_id=activity.id)
                if not is_white:
                    return Response({'error': '您没有该优惠券领取权限，请联系客户经理参与活动。'}, status=status.HTTP_400_BAD_REQUEST)
            if user.is_auth != 2 and activity.is_need_auth == 1:
                return Response({'error': '请先完成实名认证'}, status=status.HTTP_400_BAD_REQUEST)
            if activity.coupon_way == 4:
                if not alidiscountcoupon_level.is_auth:
                    return Response({'error': '您无权限派发此活动'}, status=status.HTTP_400_BAD_REQUEST)
                if activity.remain_number <= 0:
                    return Response({'error': '活动已达到派发上限'}, status=status.HTTP_400_BAD_REQUEST)
            else:
                if alidiscountcoupon_level.remain_number <= 0:
                    return Response({'error': '活动已达到派发上限'}, status=status.HTTP_400_BAD_REQUEST)
            if activity.max_number_by_day:
                begin_time = datetime.datetime.now().strftime('%Y-%m-%d 00:00:00')
                end_time = datetime.datetime.now().strftime('%Y-%m-%d 23:59:59')
                max_no = AliDiscountCouponInfo.objects.filter(alidiscountcoupon_id=activity.id, gmt_create__gte=begin_time,gmt_create__lte=end_time).count()
                if max_no >= activity.max_number_by_day:
                    return Response({'error': '今天的优惠券已领取完毕，请明天0点继续参与，感谢您对本活动的支持！'}, status=status.HTTP_400_BAD_REQUEST)
            if activity.max_number_by_user:
                max_no = AliDiscountCouponInfo.objects.filter(alidiscountcoupon_id=activity.id, customer_user_id=user.id).exclude(status=13).count()
                if max_no >= activity.max_number_by_user:
                    return Response({'error': '用户参与活动次数已达上限，感谢您对本活动的支持！'}, status=status.HTTP_400_BAD_REQUEST)
            qrcode.qrcode_state = 2
            qrcode.save()
            alidiscountcoupon_level_id = alidiscountcoupon_level.id
            activity_id = activity.id
            if activity.coupon_way == 4:
                while True:
                    activity = AliDiscountCoupon.objects.get(id=activity_id)
                    if activity.remain_number <= 0:
                        return Response({'error': '活动已达到派发上限'}, status=status.HTTP_400_BAD_REQUEST)
                    activity_origin_send_count = activity.send_count
                    activity_origin_remain_number = activity.remain_number
                    activity_new_send_count = activity_origin_send_count + 1
                    activity_new_remain_number = activity_origin_remain_number - 1
                    result = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
                        send_count=activity_new_send_count,
                        remain_number=activity_new_remain_number
                    )
                    if result == 0:
                        continue
                    break
                while True:
                    alidiscountcoupon_level = AliDiscountCouponLevel.objects.get(id=alidiscountcoupon_level_id)
                    instance_origin_take_number = alidiscountcoupon_level.take_number
                    instance_origin_receive_number = alidiscountcoupon_level.receive_number
                    instance_origin_max_number = alidiscountcoupon_level.max_number
                    instance_origin_p_take_number = alidiscountcoupon_level.p_take_number
                    instance_origin_p_receive_number = alidiscountcoupon_level.p_receive_number
                    instance_origin_p_max_number = alidiscountcoupon_level.p_max_number
                    instance_new_take_number = instance_origin_take_number + 1
                    instance_new_receive_number = instance_origin_receive_number + 1
                    instance_new_max_number = instance_origin_max_number + 1
                    instance_new_p_take_number = instance_origin_p_take_number + 1
                    instance_new_p_receive_number = instance_origin_p_receive_number + 1
                    instance_new_p_max_number = instance_origin_p_max_number + 1
                    result = AliDiscountCouponLevel.objects.filter(id=alidiscountcoupon_level_id, take_number=instance_origin_take_number).update(
                        take_number=instance_new_take_number,
                        receive_number=instance_new_receive_number,
                        max_number=instance_new_max_number,
                        p_take_number=instance_new_p_take_number,
                        p_receive_number=instance_new_p_receive_number,
                        p_max_number=instance_new_p_max_number
                    )
                    if result == 0:
                        continue
                    break
                try:
                    relation_set = alidiscountcoupon_level.child_set.all()
                    for relation in relation_set:
                        parent = relation.parent
                        parent.p_take_number += 1
                        parent.p_receive_number += 1
                        parent.p_max_number += 1
                        parent.save()
                except:
                    pass
            else:
                while True:
                    alidiscountcoupon_level = AliDiscountCouponLevel.objects.get(id=alidiscountcoupon_level_id)
                    if alidiscountcoupon_level.remain_number <= 0:
                        return Response({'error': '活动已达到派发上限'}, status=status.HTTP_400_BAD_REQUEST)
                    instance_origin_take_number = alidiscountcoupon_level.take_number
                    instance_origin_receive_number = alidiscountcoupon_level.receive_number
                    instance_origin_remain_number = alidiscountcoupon_level.remain_number
                    instance_origin_p_take_number = alidiscountcoupon_level.p_take_number
                    instance_origin_p_receive_number = alidiscountcoupon_level.p_receive_number
                    instance_origin_p_remain_number = alidiscountcoupon_level.p_remain_number
                    instance_new_take_number = instance_origin_take_number + 1
                    instance_new_receive_number = instance_origin_receive_number + 1
                    instance_new_remain_number = instance_origin_remain_number - 1
                    instance_new_p_take_number = instance_origin_p_take_number + 1
                    instance_new_p_receive_number = instance_origin_p_receive_number + 1
                    instance_new_p_remain_number = instance_origin_p_remain_number - 1
                    result = AliDiscountCouponLevel.objects.filter(id=alidiscountcoupon_level_id, take_number=instance_origin_take_number).update(
                        take_number=instance_new_take_number,
                        receive_number=instance_new_receive_number,
                        remain_number=instance_new_remain_number,
                        p_take_number=instance_new_p_take_number,
                        p_receive_number=instance_new_p_receive_number,
                        p_remain_number=instance_new_p_remain_number
                    )
                    if result == 0:
                        continue
                    break
                while True:
                    activity = AliDiscountCoupon.objects.get(id=activity_id)
                    activity_origin_send_count = activity.send_count
                    activity_origin_remain_number = activity.remain_number
                    activity_new_send_count = activity_origin_send_count + 1
                    activity_new_remain_number = activity_origin_remain_number - 1
                    result = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
                        send_count=activity_new_send_count,
                        remain_number=activity_new_remain_number
                    )
                    if result == 0:
                        continue
                    break
                try:
                    relation_set = alidiscountcoupon_level.child_set.all()
                    for relation in relation_set:
                        parent = relation.parent
                        parent.p_take_number += 1
                        parent.p_receive_number += 1
                        parent.p_remain_number -= 1
                        parent.save()
                except:
                    pass
            alidiscountcoupon_level_id = alidiscountcoupon_level.id
            activity_id = activity.id
            if activity.coupon_channel == 1:
                if not user.ali_user_id:
                    if activity.coupon_way == 4:
                        while True:
                            activity = AliDiscountCoupon.objects.get(id=activity_id)
                            activity_origin_send_count = activity.send_count
                            activity_origin_remain_number = activity.remain_number
                            activity_new_send_count = activity_origin_send_count - 1
                            activity_new_remain_number = activity_origin_remain_number + 1
                            result1 = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
                                send_count=activity_new_send_count,
                                remain_number=activity_new_remain_number
                            )
                            if result1 == 0:
                                continue
                            break
                        while True:
                            alidiscountcoupon_level = AliDiscountCouponLevel.objects.get(id=alidiscountcoupon_level_id)
                            instance_origin_take_number = alidiscountcoupon_level.take_number
                            instance_origin_receive_number = alidiscountcoupon_level.receive_number
                            instance_origin_max_number = alidiscountcoupon_level.max_number
                            instance_origin_p_take_number = alidiscountcoupon_level.p_take_number
                            instance_origin_p_receive_number = alidiscountcoupon_level.p_receive_number
                            instance_origin_p_max_number = alidiscountcoupon_level.p_max_number
                            instance_new_take_number = instance_origin_take_number - 1
                            instance_new_receive_number = instance_origin_receive_number - 1
                            instance_new_max_number = instance_origin_max_number - 1
                            instance_new_p_take_number = instance_origin_p_take_number + 1
                            instance_new_p_receive_number = instance_origin_p_receive_number - 1
                            instance_new_p_max_number = instance_origin_p_max_number - 1
                            result1 = AliDiscountCouponLevel.objects.filter(id=alidiscountcoupon_level_id, take_number=instance_origin_take_number).update(
                                take_number=instance_new_take_number,
                                receive_number=instance_new_receive_number,
                                max_number=instance_new_max_number,
                                p_take_number=instance_new_p_take_number,
                                p_receive_number=instance_new_p_receive_number,
                                p_max_number=instance_new_p_max_number
                            )
                            if result1 == 0:
                                continue
                            break
                        try:
                            relation_set = alidiscountcoupon_level.child_set.all()
                            for relation in relation_set:
                                parent = relation.parent
                                parent.p_take_number -= 1
                                parent.p_receive_number -= 1
                                parent.p_max_number -= 1
                                parent.save()
                        except:
                            pass
                    else:
                        while True:
                            alidiscountcoupon_level = AliDiscountCouponLevel.objects.get(id=alidiscountcoupon_level_id)
                            instance_origin_take_number = alidiscountcoupon_level.take_number
                            instance_origin_receive_number = alidiscountcoupon_level.receive_number
                            instance_origin_remain_number = alidiscountcoupon_level.remain_number
                            instance_origin_p_take_number = alidiscountcoupon_level.p_take_number
                            instance_origin_p_receive_number = alidiscountcoupon_level.p_receive_number
                            instance_origin_p_remain_number = alidiscountcoupon_level.p_remain_number
                            instance_new_take_number = instance_origin_take_number - 1
                            instance_new_receive_number = instance_origin_receive_number - 1
                            instance_new_remain_number = instance_origin_remain_number + 1
                            instance_new_p_take_number = instance_origin_p_take_number - 1
                            instance_new_p_receive_number = instance_origin_p_receive_number - 1
                            instance_new_p_remain_number = instance_origin_p_remain_number + 1
                            result1 = AliDiscountCouponLevel.objects.filter(id=alidiscountcoupon_level_id, take_number=instance_origin_take_number).update(
                                take_number=instance_new_take_number,
                                receive_number=instance_new_receive_number,
                                remain_number=instance_new_remain_number,
                                p_take_number=instance_new_p_take_number,
                                p_receive_number=instance_new_p_receive_number,
                                p_remain_number=instance_new_p_remain_number
                            )
                            if result1 == 0:
                                continue
                            break
                        while True:
                            activity = AliDiscountCoupon.objects.get(id=activity_id)
                            activity_origin_send_count = activity.send_count
                            activity_origin_remain_number = activity.remain_number
                            activity_new_send_count = activity_origin_send_count - 1
                            activity_new_remain_number = activity_origin_remain_number + 1
                            result1 = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
                                send_count=activity_new_send_count,
                                remain_number=activity_new_remain_number
                            )
                            if result1 == 0:
                                continue
                            break
                        try:
                            relation_set = alidiscountcoupon_level.child_set.all()
                            for relation in relation_set:
                                parent = relation.parent
                                parent.p_take_number -= 1
                                parent.p_receive_number -= 1
                                parent.p_remain_number += 1
                                parent.save()
                        except:
                            pass
                    qrcode.return_msg = '用户尚未关联支付宝,请使用支付宝【赋有】小程序授权登录'
                    qrcode.qrcode_state = 1
                    qrcode.save()
                    return Response({'error': '用户尚未关联支付宝,请使用支付宝【赋有】小程序授权登录'}, status=status.HTTP_400_BAD_REQUEST)
                alipay_obj = AlipayOpen()
                user_id = user.ali_user_id
                template_id = activity.template_id
                result = json.loads(alipay_obj.vouchersend(user_id, template_id, out_biz_no))
                if result['code'] != '10000':
                    logger.error(str(result))
                    if activity.coupon_way == 4:
                        while True:
                            activity = AliDiscountCoupon.objects.get(id=activity_id)
                            activity_origin_send_count = activity.send_count
                            activity_origin_remain_number = activity.remain_number
                            activity_new_send_count = activity_origin_send_count - 1
                            activity_new_remain_number = activity_origin_remain_number + 1
                            result1 = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
                                send_count=activity_new_send_count,
                                remain_number=activity_new_remain_number
                            )
                            if result1 == 0:
                                continue
                            break
                        while True:
                            alidiscountcoupon_level = AliDiscountCouponLevel.objects.get(id=alidiscountcoupon_level_id)
                            instance_origin_take_number = alidiscountcoupon_level.take_number
                            instance_origin_receive_number = alidiscountcoupon_level.receive_number
                            instance_origin_max_number = alidiscountcoupon_level.max_number
                            instance_origin_p_take_number = alidiscountcoupon_level.p_take_number
                            instance_origin_p_receive_number = alidiscountcoupon_level.p_receive_number
                            instance_origin_p_max_number = alidiscountcoupon_level.p_max_number
                            instance_new_take_number = instance_origin_take_number - 1
                            instance_new_receive_number = instance_origin_receive_number - 1
                            instance_new_max_number = instance_origin_max_number - 1
                            instance_new_p_take_number = instance_origin_p_take_number + 1
                            instance_new_p_receive_number = instance_origin_p_receive_number - 1
                            instance_new_p_max_number = instance_origin_p_max_number - 1
                            result1 = AliDiscountCouponLevel.objects.filter(id=alidiscountcoupon_level_id, take_number=instance_origin_take_number).update(
                                take_number=instance_new_take_number,
                                receive_number=instance_new_receive_number,
                                max_number=instance_new_max_number,
                                p_take_number=instance_new_p_take_number,
                                p_receive_number=instance_new_p_receive_number,
                                p_max_number=instance_new_p_max_number
                            )
                            if result1 == 0:
                                continue
                            break
                        try:
                            relation_set = alidiscountcoupon_level.child_set.all()
                            for relation in relation_set:
                                parent = relation.parent
                                parent.p_take_number -= 1
                                parent.p_receive_number -= 1
                                parent.p_max_number -= 1
                                parent.save()
                        except:
                            pass
                    else:
                        while True:
                            alidiscountcoupon_level = AliDiscountCouponLevel.objects.get(id=alidiscountcoupon_level_id)
                            instance_origin_take_number = alidiscountcoupon_level.take_number
                            instance_origin_receive_number = alidiscountcoupon_level.receive_number
                            instance_origin_remain_number = alidiscountcoupon_level.remain_number
                            instance_origin_p_take_number = alidiscountcoupon_level.p_take_number
                            instance_origin_p_receive_number = alidiscountcoupon_level.p_receive_number
                            instance_origin_p_remain_number = alidiscountcoupon_level.p_remain_number
                            instance_new_take_number = instance_origin_take_number - 1
                            instance_new_receive_number = instance_origin_receive_number - 1
                            instance_new_remain_number = instance_origin_remain_number + 1
                            instance_new_p_take_number = instance_origin_p_take_number - 1
                            instance_new_p_receive_number = instance_origin_p_receive_number - 1
                            instance_new_p_remain_number = instance_origin_p_remain_number + 1
                            result1 = AliDiscountCouponLevel.objects.filter(id=alidiscountcoupon_level_id, take_number=instance_origin_take_number).update(
                                take_number=instance_new_take_number,
                                receive_number=instance_new_receive_number,
                                remain_number=instance_new_remain_number,
                                p_take_number=instance_new_p_take_number,
                                p_receive_number=instance_new_p_receive_number,
                                p_remain_number=instance_new_p_remain_number
                            )
                            if result1 == 0:
                                continue
                            break
                        while True:
                            activity = AliDiscountCoupon.objects.get(id=activity_id)
                            activity_origin_send_count = activity.send_count
                            activity_origin_remain_number = activity.remain_number
                            activity_new_send_count = activity_origin_send_count - 1
                            activity_new_remain_number = activity_origin_remain_number + 1
                            result1 = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
                                send_count=activity_new_send_count,
                                remain_number=activity_new_remain_number
                            )
                            if result1 == 0:
                                continue
                            break
                        try:
                            relation_set = alidiscountcoupon_level.child_set.all()
                            for relation in relation_set:
                                parent = relation.parent
                                parent.p_take_number -= 1
                                parent.p_receive_number -= 1
                                parent.p_remain_number += 1
                                parent.save()
                        except:
                            pass
                    qrcode.return_msg = result['sub_msg']
                    qrcode.qrcode_state = 1
                    qrcode.save()
                    try:
                        return Response({'error': result['sub_msg']}, status=status.HTTP_400_BAD_REQUEST)
                    except:
                        return Response({'error': '领取失败,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
                voucher_id = result['voucher_id']
                if activity.platform_id == 1:
                    result = json.loads(alipay_obj.voucherquery(voucher_id))
                    data = {
                        'alidiscountcoupon_id': activity.id,
                        'voucher_id': voucher_id,
                        'user_id': user_id,
                        'template_id': result['template_id'],
                        'gmt_active': result['gmt_active'],
                        'gmt_expired': result['gmt_expired'],
                        'total_amount': result['total_amount'],
                        'gmt_create': result['gmt_create'],
                        'available_amount': result['available_amount'],
                        'name': result['name'],
                        'out_biz_no': out_biz_no,
                        'customer_user_id': user.id,
                        'companyuser_id': qrcode.companyuser_id,
                        'gmt_distributed': qrcode.gmt_distributed,
                        'alidiscountcoupon_level_id': alidiscountcoupon_level.id,
                        'level_id': alidiscountcoupon_level.level_id,
                        'mobile': user.mobile,
                        'coupon_channel': activity.coupon_channel
                    }
                else:
                    gmt_create = datetime.datetime.now()
                    alidiscountcouponchannelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
                    if alidiscountcouponchannelcommonvoucher.usetime_type == 2:
                        gmt_expired = alidiscountcouponchannelcommonvoucher.end_fixed_time
                        gmt_active = alidiscountcouponchannelcommonvoucher.start_fixed_time
                    elif alidiscountcouponchannelcommonvoucher.usetime_type == 3:
                        gmt_expired = gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)
                        gmt_active = gmt_create
                    else:
                        gmt_active = (gmt_create + datetime.timedelta(days=1)).strftime("%Y-%m-%d 00:00:00")
                        gmt_expired = (gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)).strftime("%Y-%m-%d 23:59:59")
                    data = {
                        'alidiscountcoupon_id': activity.id,
                        'voucher_id': voucher_id,
                        'user_id': user_id,
                        'template_id': activity.template_id,
                        'gmt_active': gmt_active,
                        'gmt_expired': gmt_expired,
                        'total_amount': activity.amount,
                        'gmt_create': gmt_create,
                        'available_amount': activity.amount,
                        'name': activity.activity_name,
                        'out_biz_no': out_biz_no,
                        'customer_user_id': user.id,
                        'companyuser_id': qrcode.companyuser_id,
                        'gmt_distributed': gmt_create,
                        'alidiscountcoupon_level_id': alidiscountcoupon_level.id,
                        'level_id': alidiscountcoupon_level.level_id,
                        'mobile': user.mobile,
                        'coupon_channel': activity.coupon_channel
                    }
                if not user.level_id:
                    user.level_id = alidiscountcoupon_level.level_id
                    user.user_id = qrcode.companyuser_id
                    user.save()
                voucherinfo, create = AliDiscountCouponInfo.objects.get_or_create(defaults=data, voucher_id=voucher_id)
                if create:
                    return Response({'success': '领取成功', 'coupon_id': voucherinfo.id}, status=status.HTTP_200_OK)
                else:
                    return Response({'error': '已经领取过了'}, status=status.HTTP_400_BAD_REQUEST)
            elif activity.coupon_channel == 2:
                if user.new_openid:
                    appid = settings.CUSTOMER_APP_ID_NEW
                    openid = user.new_openid
                elif user.openid:
                    appid = settings.CUSTOMER_APP_ID
                    openid = user.openid
                else:
                    if activity.coupon_way == 4:
                        while True:
                            activity = AliDiscountCoupon.objects.get(id=activity_id)
                            activity_origin_send_count = activity.send_count
                            activity_origin_remain_number = activity.remain_number
                            activity_new_send_count = activity_origin_send_count - 1
                            activity_new_remain_number = activity_origin_remain_number + 1
                            result1 = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
                                send_count=activity_new_send_count,
                                remain_number=activity_new_remain_number
                            )
                            if result1 == 0:
                                continue
                            break
                        while True:
                            alidiscountcoupon_level = AliDiscountCouponLevel.objects.get(id=alidiscountcoupon_level_id)
                            instance_origin_take_number = alidiscountcoupon_level.take_number
                            instance_origin_receive_number = alidiscountcoupon_level.receive_number
                            instance_origin_max_number = alidiscountcoupon_level.max_number
                            instance_origin_p_take_number = alidiscountcoupon_level.p_take_number
                            instance_origin_p_receive_number = alidiscountcoupon_level.p_receive_number
                            instance_origin_p_max_number = alidiscountcoupon_level.p_max_number
                            instance_new_take_number = instance_origin_take_number - 1
                            instance_new_receive_number = instance_origin_receive_number - 1
                            instance_new_max_number = instance_origin_max_number - 1
                            instance_new_p_take_number = instance_origin_p_take_number + 1
                            instance_new_p_receive_number = instance_origin_p_receive_number - 1
                            instance_new_p_max_number = instance_origin_p_max_number - 1
                            result1 = AliDiscountCouponLevel.objects.filter(id=alidiscountcoupon_level_id, take_number=instance_origin_take_number).update(
                                take_number=instance_new_take_number,
                                receive_number=instance_new_receive_number,
                                max_number=instance_new_max_number,
                                p_take_number=instance_new_p_take_number,
                                p_receive_number=instance_new_p_receive_number,
                                p_max_number=instance_new_p_max_number
                            )
                            if result1 == 0:
                                continue
                            break
                        try:
                            relation_set = alidiscountcoupon_level.child_set.all()
                            for relation in relation_set:
                                parent = relation.parent
                                parent.p_take_number -= 1
                                parent.p_receive_number -= 1
                                parent.p_max_number -= 1
                                parent.save()
                        except:
                            pass
                    else:
                        while True:
                            alidiscountcoupon_level = AliDiscountCouponLevel.objects.get(id=alidiscountcoupon_level_id)
                            instance_origin_take_number = alidiscountcoupon_level.take_number
                            instance_origin_receive_number = alidiscountcoupon_level.receive_number
                            instance_origin_remain_number = alidiscountcoupon_level.remain_number
                            instance_origin_p_take_number = alidiscountcoupon_level.p_take_number
                            instance_origin_p_receive_number = alidiscountcoupon_level.p_receive_number
                            instance_origin_p_remain_number = alidiscountcoupon_level.p_remain_number
                            instance_new_take_number = instance_origin_take_number - 1
                            instance_new_receive_number = instance_origin_receive_number - 1
                            instance_new_remain_number = instance_origin_remain_number + 1
                            instance_new_p_take_number = instance_origin_p_take_number - 1
                            instance_new_p_receive_number = instance_origin_p_receive_number - 1
                            instance_new_p_remain_number = instance_origin_p_remain_number + 1
                            result1 = AliDiscountCouponLevel.objects.filter(id=alidiscountcoupon_level_id, take_number=instance_origin_take_number).update(
                                take_number=instance_new_take_number,
                                receive_number=instance_new_receive_number,
                                remain_number=instance_new_remain_number,
                                p_take_number=instance_new_p_take_number,
                                p_receive_number=instance_new_p_receive_number,
                                p_remain_number=instance_new_p_remain_number
                            )
                            if result1 == 0:
                                continue
                            break
                        while True:
                            activity = AliDiscountCoupon.objects.get(id=activity_id)
                            activity_origin_send_count = activity.send_count
                            activity_origin_remain_number = activity.remain_number
                            activity_new_send_count = activity_origin_send_count - 1
                            activity_new_remain_number = activity_origin_remain_number + 1
                            result1 = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
                                send_count=activity_new_send_count,
                                remain_number=activity_new_remain_number
                            )
                            if result1 == 0:
                                continue
                            break
                        try:
                            relation_set = alidiscountcoupon_level.child_set.all()
                            for relation in relation_set:
                                parent = relation.parent
                                parent.p_take_number -= 1
                                parent.p_receive_number -= 1
                                parent.p_remain_number += 1
                                parent.save()
                        except:
                            pass
                    return Response({'error': '用户尚未关联微信,请使用微信【赋有】小程序授权登录'}, status=status.HTTP_400_BAD_REQUEST)
                if activity.platform_id == 13:
                    distribute_channel = Channel.objects.get(id=13)
                else:
                    distribute_channel = Channel.objects.get(id=9)
                data_json = {
                    "stock_id": activity.template_id,
                    "out_request_no": out_biz_no,
                    "appid": appid,
                    "stock_creator_mchid": activity.platform.mchid
                }
                data_dict = favor_distributed_coupons_sichun(data_json, openid, distribute_channel)
                if 'code' in data_dict:
                    if activity.coupon_way == 4:
                        while True:
                            activity = AliDiscountCoupon.objects.get(id=activity_id)
                            activity_origin_send_count = activity.send_count
                            activity_origin_remain_number = activity.remain_number
                            activity_new_send_count = activity_origin_send_count - 1
                            activity_new_remain_number = activity_origin_remain_number + 1
                            result1 = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
                                send_count=activity_new_send_count,
                                remain_number=activity_new_remain_number
                            )
                            if result1 == 0:
                                continue
                            break
                        while True:
                            alidiscountcoupon_level = AliDiscountCouponLevel.objects.get(id=alidiscountcoupon_level_id)
                            instance_origin_take_number = alidiscountcoupon_level.take_number
                            instance_origin_receive_number = alidiscountcoupon_level.receive_number
                            instance_origin_max_number = alidiscountcoupon_level.max_number
                            instance_origin_p_take_number = alidiscountcoupon_level.p_take_number
                            instance_origin_p_receive_number = alidiscountcoupon_level.p_receive_number
                            instance_origin_p_max_number = alidiscountcoupon_level.p_max_number
                            instance_new_take_number = instance_origin_take_number - 1
                            instance_new_receive_number = instance_origin_receive_number - 1
                            instance_new_max_number = instance_origin_max_number - 1
                            instance_new_p_take_number = instance_origin_p_take_number + 1
                            instance_new_p_receive_number = instance_origin_p_receive_number - 1
                            instance_new_p_max_number = instance_origin_p_max_number - 1
                            result1 = AliDiscountCouponLevel.objects.filter(id=alidiscountcoupon_level_id, take_number=instance_origin_take_number).update(
                                take_number=instance_new_take_number,
                                receive_number=instance_new_receive_number,
                                max_number=instance_new_max_number,
                                p_take_number=instance_new_p_take_number,
                                p_receive_number=instance_new_p_receive_number,
                                p_max_number=instance_new_p_max_number
                            )
                            if result1 == 0:
                                continue
                            break
                        try:
                            relation_set = alidiscountcoupon_level.child_set.all()
                            for relation in relation_set:
                                parent = relation.parent
                                parent.p_take_number -= 1
                                parent.p_receive_number -= 1
                                parent.p_max_number -= 1
                                parent.save()
                        except:
                            pass
                    else:
                        while True:
                            alidiscountcoupon_level = AliDiscountCouponLevel.objects.get(id=alidiscountcoupon_level_id)
                            instance_origin_take_number = alidiscountcoupon_level.take_number
                            instance_origin_receive_number = alidiscountcoupon_level.receive_number
                            instance_origin_remain_number = alidiscountcoupon_level.remain_number
                            instance_origin_p_take_number = alidiscountcoupon_level.p_take_number
                            instance_origin_p_receive_number = alidiscountcoupon_level.p_receive_number
                            instance_origin_p_remain_number = alidiscountcoupon_level.p_remain_number
                            instance_new_take_number = instance_origin_take_number - 1
                            instance_new_receive_number = instance_origin_receive_number - 1
                            instance_new_remain_number = instance_origin_remain_number + 1
                            instance_new_p_take_number = instance_origin_p_take_number - 1
                            instance_new_p_receive_number = instance_origin_p_receive_number - 1
                            instance_new_p_remain_number = instance_origin_p_remain_number + 1
                            result1 = AliDiscountCouponLevel.objects.filter(id=alidiscountcoupon_level_id, take_number=instance_origin_take_number).update(
                                take_number=instance_new_take_number,
                                receive_number=instance_new_receive_number,
                                remain_number=instance_new_remain_number,
                                p_take_number=instance_new_p_take_number,
                                p_receive_number=instance_new_p_receive_number,
                                p_remain_number=instance_new_p_remain_number
                            )
                            if result1 == 0:
                                continue
                            break
                        while True:
                            activity = AliDiscountCoupon.objects.get(id=activity_id)
                            activity_origin_send_count = activity.send_count
                            activity_origin_remain_number = activity.remain_number
                            activity_new_send_count = activity_origin_send_count - 1
                            activity_new_remain_number = activity_origin_remain_number + 1
                            result1 = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
                                send_count=activity_new_send_count,
                                remain_number=activity_new_remain_number
                            )
                            if result1 == 0:
                                continue
                            break
                        try:
                            relation_set = alidiscountcoupon_level.child_set.all()
                            for relation in relation_set:
                                parent = relation.parent
                                parent.p_take_number -= 1
                                parent.p_receive_number -= 1
                                parent.p_remain_number += 1
                                parent.save()
                        except:
                            pass
                    return Response({'error': data_dict['message']}, status=status.HTTP_400_BAD_REQUEST)
                coupon_id = data_dict['coupon_id']
                result = favor_query_coupons_sichun(coupon_id, openid, appid, distribute_channel)
                data = {
                    'alidiscountcoupon_id': activity.id,
                    'voucher_id': coupon_id,
                    'user_id': openid,
                    'template_id': result['stock_id'],
                    'gmt_active': result['available_begin_time'].replace('T', ' ').replace('+08:00', ''),
                    'gmt_expired': result['available_end_time'].replace('T', ' ').replace('+08:00', ''),
                    'total_amount': result['normal_coupon_information']['coupon_amount']/100,
                    'gmt_create': datetime.datetime.now(),
                    'available_amount': result['normal_coupon_information']['coupon_amount']/100,
                    'name': result['coupon_name'],
                    'out_biz_no': out_biz_no,
                    'customer_user_id': user.id,
                    'companyuser_id': qrcode.companyuser_id,
                    'gmt_distributed': qrcode.gmt_distributed,
                    'alidiscountcoupon_level_id': alidiscountcoupon_level.id,
                    'level_id': alidiscountcoupon_level.level_id,
                    'mobile': user.mobile,
                    'coupon_channel': activity.coupon_channel
                }
                if not user.level_id:
                    user.level_id = alidiscountcoupon_level.level_id
                    user.user_id = qrcode.companyuser_id
                    user.save()
                voucherinfo, create = AliDiscountCouponInfo.objects.get_or_create(defaults=data, voucher_id=coupon_id)
                if create:
                    return Response({'success': '领取成功', 'coupon_id': voucherinfo.id}, status=status.HTTP_200_OK)
                else:
                    return Response({'error': '已经领取过了'}, status=status.HTTP_400_BAD_REQUEST)
            elif activity.coupon_channel == 5:
                meituan_result = favor_meituan_coupons(out_biz_no, activity.template_id, user.mobile)
                if meituan_result['status'] != 'success':
                    if activity.coupon_way == 4:
                        while True:
                            activity = AliDiscountCoupon.objects.get(id=activity_id)
                            activity_origin_send_count = activity.send_count
                            activity_origin_remain_number = activity.remain_number
                            activity_new_send_count = activity_origin_send_count - 1
                            activity_new_remain_number = activity_origin_remain_number + 1
                            result1 = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
                                send_count=activity_new_send_count,
                                remain_number=activity_new_remain_number
                            )
                            if result1 == 0:
                                continue
                            break
                        while True:
                            alidiscountcoupon_level = AliDiscountCouponLevel.objects.get(id=alidiscountcoupon_level_id)
                            instance_origin_take_number = alidiscountcoupon_level.take_number
                            instance_origin_receive_number = alidiscountcoupon_level.receive_number
                            instance_origin_max_number = alidiscountcoupon_level.max_number
                            instance_origin_p_take_number = alidiscountcoupon_level.p_take_number
                            instance_origin_p_receive_number = alidiscountcoupon_level.p_receive_number
                            instance_origin_p_max_number = alidiscountcoupon_level.p_max_number
                            instance_new_take_number = instance_origin_take_number - 1
                            instance_new_receive_number = instance_origin_receive_number - 1
                            instance_new_max_number = instance_origin_max_number - 1
                            instance_new_p_take_number = instance_origin_p_take_number + 1
                            instance_new_p_receive_number = instance_origin_p_receive_number - 1
                            instance_new_p_max_number = instance_origin_p_max_number - 1
                            result1 = AliDiscountCouponLevel.objects.filter(id=alidiscountcoupon_level_id, take_number=instance_origin_take_number).update(
                                take_number=instance_new_take_number,
                                receive_number=instance_new_receive_number,
                                max_number=instance_new_max_number,
                                p_take_number=instance_new_p_take_number,
                                p_receive_number=instance_new_p_receive_number,
                                p_max_number=instance_new_p_max_number
                            )
                            if result1 == 0:
                                continue
                            break
                        try:
                            relation_set = alidiscountcoupon_level.child_set.all()
                            for relation in relation_set:
                                parent = relation.parent
                                parent.p_take_number -= 1
                                parent.p_receive_number -= 1
                                parent.p_max_number -= 1
                                parent.save()
                        except:
                            pass
                    else:
                        while True:
                            alidiscountcoupon_level = AliDiscountCouponLevel.objects.get(id=alidiscountcoupon_level_id)
                            instance_origin_take_number = alidiscountcoupon_level.take_number
                            instance_origin_receive_number = alidiscountcoupon_level.receive_number
                            instance_origin_remain_number = alidiscountcoupon_level.remain_number
                            instance_origin_p_take_number = alidiscountcoupon_level.p_take_number
                            instance_origin_p_receive_number = alidiscountcoupon_level.p_receive_number
                            instance_origin_p_remain_number = alidiscountcoupon_level.p_remain_number
                            instance_new_take_number = instance_origin_take_number - 1
                            instance_new_receive_number = instance_origin_receive_number - 1
                            instance_new_remain_number = instance_origin_remain_number + 1
                            instance_new_p_take_number = instance_origin_p_take_number - 1
                            instance_new_p_receive_number = instance_origin_p_receive_number - 1
                            instance_new_p_remain_number = instance_origin_p_remain_number + 1
                            result1 = AliDiscountCouponLevel.objects.filter(id=alidiscountcoupon_level_id, take_number=instance_origin_take_number).update(
                                take_number=instance_new_take_number,
                                receive_number=instance_new_receive_number,
                                remain_number=instance_new_remain_number,
                                p_take_number=instance_new_p_take_number,
                                p_receive_number=instance_new_p_receive_number,
                                p_remain_number=instance_new_p_remain_number
                            )
                            if result1 == 0:
                                continue
                            break
                        while True:
                            activity = AliDiscountCoupon.objects.get(id=activity_id)
                            activity_origin_send_count = activity.send_count
                            activity_origin_remain_number = activity.remain_number
                            activity_new_send_count = activity_origin_send_count - 1
                            activity_new_remain_number = activity_origin_remain_number + 1
                            result1 = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
                                send_count=activity_new_send_count,
                                remain_number=activity_new_remain_number
                            )
                            if result1 == 0:
                                continue
                            break
                        try:
                            relation_set = alidiscountcoupon_level.child_set.all()
                            for relation in relation_set:
                                parent = relation.parent
                                parent.p_take_number -= 1
                                parent.p_receive_number -= 1
                                parent.p_remain_number += 1
                                parent.save()
                        except:
                            pass
                    return Response({'error': meituan_result['errorMsg']}, status=status.HTTP_400_BAD_REQUEST)
                coupon_id = meituan_result['data'][0]['code']
                user_id = user.mobile
                gmt_create = datetime.datetime.now()
                alidiscountcouponchannelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
                if alidiscountcouponchannelcommonvoucher.usetime_type == 2:
                    gmt_expired = alidiscountcouponchannelcommonvoucher.end_fixed_time
                    gmt_active = alidiscountcouponchannelcommonvoucher.start_fixed_time
                elif alidiscountcouponchannelcommonvoucher.usetime_type == 3:
                    gmt_expired = gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)
                    gmt_active = gmt_create
                else:
                    gmt_active = (gmt_create + datetime.timedelta(days=1)).strftime("%Y-%m-%d 00:00:00")
                    gmt_expired =(gmt_create+ datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)).strftime("%Y-%m-%d 23:59:59")
                data = {
                    'alidiscountcoupon_id': activity.id,
                    'voucher_id': coupon_id,
                    'user_id': user_id,
                    'template_id': activity.template_id,
                    'gmt_active': gmt_active,
                    'gmt_expired': gmt_expired,
                    'total_amount': activity.amount,
                    'gmt_create': gmt_create,
                    'available_amount': activity.amount,
                    'name': activity.activity_name,
                    'out_biz_no': out_biz_no,
                    'customer_user_id': user.id,
                    'companyuser_id': qrcode.companyuser_id,
                    'gmt_distributed': qrcode.gmt_distributed,
                    'alidiscountcoupon_level_id': alidiscountcoupon_level.id,
                    'level_id': alidiscountcoupon_level.level_id,
                    'mobile': user.mobile,
                    'coupon_channel': activity.coupon_channel
                }
                if not user.level_id:
                    user.level_id = alidiscountcoupon_level.level_id
                    user.user_id = qrcode.companyuser_id
                    user.save()
                voucherinfo, create = AliDiscountCouponInfo.objects.get_or_create(defaults=data, out_biz_no=out_biz_no)
                if create:
                    return Response({'success': '领取成功', 'coupon_id': voucherinfo.id}, status=status.HTTP_200_OK)
                else:
                    return Response({'error': '已经领取过了'}, status=status.HTTP_400_BAD_REQUEST)
            else:
                voucher_id = f'{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}{random_str(14)}'
                user_id = user.ali_user_id
                gmt_create = datetime.datetime.now()
                alidiscountcouponchannelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
                if alidiscountcouponchannelcommonvoucher.usetime_type == 2:
                    gmt_expired = alidiscountcouponchannelcommonvoucher.end_fixed_time
                    gmt_active = alidiscountcouponchannelcommonvoucher.start_fixed_time
                elif alidiscountcouponchannelcommonvoucher.usetime_type == 3:
                    gmt_expired = gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)
                    gmt_active = gmt_create
                else:
                    gmt_active = (gmt_create + datetime.timedelta(days=1)).strftime("%Y-%m-%d 00:00:00")
                    gmt_expired =(gmt_create+ datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)).strftime("%Y-%m-%d 23:59:59")
                data = {
                    'alidiscountcoupon_id': activity.id,
                    'voucher_id': voucher_id,
                    'user_id': user_id,
                    'template_id': activity.template_id,
                    'gmt_active': gmt_active,
                    'gmt_expired': gmt_expired,
                    'total_amount': activity.amount,
                    'gmt_create': gmt_create,
                    'available_amount': activity.amount,
                    'name': activity.activity_name,
                    'out_biz_no': out_biz_no,
                    'customer_user_id': user.id,
                    'companyuser_id': qrcode.companyuser_id,
                    'gmt_distributed': qrcode.gmt_distributed,
                    'alidiscountcoupon_level_id': alidiscountcoupon_level.id,
                    'level_id': alidiscountcoupon_level.level_id,
                    'mobile': user.mobile,
                    'coupon_channel': activity.coupon_channel
                }
                if not user.level_id:
                    user.level_id = alidiscountcoupon_level.level_id
                    user.user_id = qrcode.companyuser_id
                    user.save()
                voucherinfo, create = AliDiscountCouponInfo.objects.get_or_create(defaults=data, out_biz_no=out_biz_no)
                if create:
                    return Response({'success': '领取成功', 'coupon_id': voucherinfo.id}, status=status.HTTP_200_OK)
                else:
                    return Response({'error': '已经领取过了'}, status=status.HTTP_400_BAD_REQUEST)
        elif len(identify) == 48:
            try:
                alidiscountcouponmanagerqrcode = AliDiscountCouponManagerQRCode.objects.get(identify=identify)
            except:
                return Response({'error': '无效二维码,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
            if alidiscountcouponmanagerqrcode.qrcode_dimension == 1:
                companyuser_id = alidiscountcouponmanagerqrcode.companyuser_id
                level_id = alidiscountcouponmanagerqrcode.companyuser.level_id
            else:
                companyuser_id = None
                level_id = alidiscountcouponmanagerqrcode.level_id
            out_biz_no = f'100004{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
            activity = alidiscountcouponmanagerqrcode.alidiscountcoupon
            alidiscountcoupon_level = alidiscountcouponmanagerqrcode.alidiscountcoupon_level
            try:
                channelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
                if channelcommonvoucher.distributed_limit_by_time == 1:
                    week = str(datetime.datetime.now().weekday())
                    enable_time = datetime.datetime.now().strftime('1970-01-01 %H:%M:%S')
                    alidiscountcoupondstributedlimit = AliDiscountCouponDistributedLimit.objects.filter(ali_discount_coupon_common_voucher_id=channelcommonvoucher.id, weeks__contains=week, start_enable_time__lte=enable_time, end_enable_time__gte=enable_time)
                    if not alidiscountcoupondstributedlimit:
                        return Response({'error': '没到活动派发时间'}, status=status.HTTP_400_BAD_REQUEST)
            except:
                pass
            if activity.is_white:
                is_white = AliDiscountCouponWhiteTable.objects.filter(mobile=user.mobile, alidiscountcoupon_id=activity.id)
                if not is_white:
                    return Response({'error': '您没有该优惠券领取权限，请联系客户经理参与活动。'}, status=status.HTTP_400_BAD_REQUEST)
            if activity.is_check_identity == 1:
                check_manager = User.objects.filter(mobile=user.mobile, is_active=1)
                if check_manager:
                    return Response({'error': '该活动暂不允许内部员工领取，如有疑问请咨询客服。'}, status=status.HTTP_400_BAD_REQUEST)
            if user.is_auth != 2 and activity.is_need_auth == 1:
                return Response({'error': '请先完成实名认证'}, status=status.HTTP_400_BAD_REQUEST)
            if activity.max_number_by_day:
                begin_time = datetime.datetime.now().strftime('%Y-%m-%d 00:00:00')
                end_time = datetime.datetime.now().strftime('%Y-%m-%d 23:59:59')
                max_no = AliDiscountCouponInfo.objects.filter(alidiscountcoupon_id=activity.id, gmt_create__gte=begin_time,gmt_create__lte=end_time).count()
                if max_no >= activity.max_number_by_day:
                    return Response({'error': '今天的优惠券已领取完毕，请明天0点继续参与，感谢您对本活动的支持！'}, status=status.HTTP_400_BAD_REQUEST)
            if activity.max_number_by_user:
                max_no = AliDiscountCouponInfo.objects.filter(alidiscountcoupon_id=activity.id, customer_user_id=user.id).exclude(status=13).count()
                if max_no >= activity.max_number_by_user:
                    return Response({'error': '用户参与活动次数已达上限，感谢您对本活动的支持！'}, status=status.HTTP_400_BAD_REQUEST)
            if alidiscountcoupon_level.remain_number <= 0:
                return Response({'error': '活动已达到派发上限'}, status=status.HTTP_400_BAD_REQUEST)
            alidiscountcoupon_level_id = alidiscountcoupon_level.id
            activity_id = activity.id
            if activity.coupon_channel == 1:
                if not user.ali_user_id:
                    return Response({'error': '用户尚未关联支付宝,请使用支付宝【赋有】小程序授权登录'}, status=status.HTTP_400_BAD_REQUEST)
                alipay_obj = AlipayOpen()
                user_id = user.ali_user_id
                template_id = activity.template_id
                result = json.loads(alipay_obj.vouchersend(user_id, template_id, out_biz_no))
                if result['code'] != '10000':
                    logger.error(str(result))
                    try:
                        return Response({'error': result['sub_msg']}, status=status.HTTP_400_BAD_REQUEST)
                    except:
                        return Response({'error': '领取失败,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
                voucher_id = result['voucher_id']
                if activity.platform_id == 1:
                    result = json.loads(alipay_obj.voucherquery(voucher_id))
                    data = {
                        'alidiscountcoupon_id': activity.id,
                        'voucher_id': voucher_id,
                        'user_id': user_id,
                        'template_id': result['template_id'],
                        'gmt_active': result['gmt_active'],
                        'gmt_expired': result['gmt_expired'],
                        'total_amount': result['total_amount'],
                        'gmt_create': result['gmt_create'],
                        'available_amount': result['available_amount'],
                        'name': result['name'],
                        'out_biz_no': out_biz_no,
                        'customer_user_id': user.id,
                        'gmt_distributed': datetime.datetime.now(),
                        'alidiscountcoupon_level_id': alidiscountcoupon_level.id,
                        'level_id': level_id,
                        'mobile': user.mobile,
                        'companyuser_id': companyuser_id,
                        'coupon_channel': activity.coupon_channel
                    }
                else:
                    gmt_create = datetime.datetime.now()
                    alidiscountcouponchannelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
                    if alidiscountcouponchannelcommonvoucher.usetime_type == 2:
                        gmt_expired = alidiscountcouponchannelcommonvoucher.end_fixed_time
                        gmt_active = alidiscountcouponchannelcommonvoucher.start_fixed_time
                    elif alidiscountcouponchannelcommonvoucher.usetime_type == 3:
                        gmt_expired = gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)
                        gmt_active = gmt_create
                    else:
                        gmt_active = (gmt_create + datetime.timedelta(days=1)).strftime("%Y-%m-%d 00:00:00")
                        gmt_expired = (gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)).strftime("%Y-%m-%d 23:59:59")
                    data = {
                        'alidiscountcoupon_id': activity.id,
                        'voucher_id': voucher_id,
                        'user_id': user_id,
                        'template_id': activity.template_id,
                        'gmt_active': gmt_active,
                        'gmt_expired': gmt_expired,
                        'total_amount': activity.amount,
                        'gmt_create': gmt_create,
                        'available_amount': activity.amount,
                        'name': activity.activity_name,
                        'out_biz_no': out_biz_no,
                        'customer_user_id': user.id,
                        'gmt_distributed': gmt_create,
                        'alidiscountcoupon_level_id': alidiscountcoupon_level.id,
                        'level_id': level_id,
                        'mobile': user.mobile,
                        'companyuser_id': companyuser_id,
                        'coupon_channel': activity.coupon_channel
                    }
                voucherinfo, create = AliDiscountCouponInfo.objects.get_or_create(defaults=data, voucher_id=voucher_id)
                while True:
                    alidiscountcoupon_level = AliDiscountCouponLevel.objects.get(id=alidiscountcoupon_level_id)
                    instance_origin_take_number = alidiscountcoupon_level.take_number
                    instance_origin_receive_number = alidiscountcoupon_level.receive_number
                    instance_origin_remain_number = alidiscountcoupon_level.remain_number
                    instance_origin_p_take_number = alidiscountcoupon_level.p_take_number
                    instance_origin_p_receive_number = alidiscountcoupon_level.p_receive_number
                    instance_origin_p_remain_number = alidiscountcoupon_level.p_remain_number
                    instance_new_take_number = instance_origin_take_number + 1
                    instance_new_receive_number = instance_origin_receive_number + 1
                    instance_new_remain_number = instance_origin_remain_number - 1
                    instance_new_p_take_number = instance_origin_p_take_number + 1
                    instance_new_p_receive_number = instance_origin_p_receive_number + 1
                    instance_new_p_remain_number = instance_origin_p_remain_number - 1
                    result = AliDiscountCouponLevel.objects.filter(id=alidiscountcoupon_level_id, take_number=instance_origin_take_number).update(
                        take_number=instance_new_take_number,
                        receive_number=instance_new_receive_number,
                        remain_number=instance_new_remain_number,
                        p_take_number=instance_new_p_take_number,
                        p_receive_number=instance_new_p_receive_number,
                        p_remain_number=instance_new_p_remain_number
                    )
                    if result == 0:
                        continue
                    break
                while True:
                    activity = AliDiscountCoupon.objects.get(id=activity_id)
                    activity_origin_send_count = activity.send_count
                    activity_origin_remain_number = activity.remain_number
                    activity_new_send_count = activity_origin_send_count + 1
                    activity_new_remain_number = activity_origin_remain_number - 1
                    result = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
                        send_count=activity_new_send_count,
                        remain_number=activity_new_remain_number
                    )
                    if result == 0:
                        continue
                    break
                try:
                    relation_set = alidiscountcoupon_level.child_set.all()
                    for relation in relation_set:
                        parent = relation.parent
                        parent.p_take_number += 1
                        parent.p_receive_number += 1
                        parent.p_remain_number -= 1
                        parent.save()
                except:
                    pass
                if create:
                    return Response({'success': '领取成功', 'coupon_id': voucherinfo.id}, status=status.HTTP_200_OK)
                else:
                    return Response({'error': '已经领取过了'}, status=status.HTTP_400_BAD_REQUEST)
            elif activity.coupon_channel == 2:
                if user.new_openid:
                    appid = settings.CUSTOMER_APP_ID_NEW
                    openid = user.new_openid
                elif user.openid:
                    appid = settings.CUSTOMER_APP_ID
                    openid = user.openid
                else:
                    return Response({'error': '用户尚未关联微信,请使用微信【赋有】小程序授权登录'}, status=status.HTTP_400_BAD_REQUEST)
                if activity.platform_id == 13:
                    distribute_channel = Channel.objects.get(id=13)
                else:
                    distribute_channel = Channel.objects.get(id=4)
                data_json = {
                    "stock_id": activity.template_id,
                    "out_request_no": out_biz_no,
                    "appid": appid,
                    "stock_creator_mchid": activity.platform.mchid
                }
                data_dict = favor_distributed_coupons_sichun(data_json, openid, distribute_channel)
                if 'code' in data_dict:
                    return Response({'error': data_dict['message']}, status=status.HTTP_400_BAD_REQUEST)
                coupon_id = data_dict['coupon_id']
                result = favor_query_coupons_sichun(coupon_id, openid, appid, distribute_channel)
                data = {
                    'alidiscountcoupon_id': activity.id,
                    'voucher_id': coupon_id,
                    'user_id': openid,
                    'template_id': result['stock_id'],
                    'gmt_active': result['available_begin_time'].replace('T', ' ').replace('+08:00', ''),
                    'gmt_expired': result['available_end_time'].replace('T', ' ').replace('+08:00', ''),
                    'total_amount': result['normal_coupon_information']['coupon_amount']/100,
                    'gmt_create': datetime.datetime.now(),
                    'available_amount': result['normal_coupon_information']['coupon_amount']/100,
                    'name': result['coupon_name'],
                    'out_biz_no': out_biz_no,
                    'customer_user_id': user.id,
                    'gmt_distributed': datetime.datetime.now(),
                    'alidiscountcoupon_level_id': alidiscountcoupon_level.id,
                    'level_id': level_id,
                    'mobile': user.mobile,
                    'companyuser_id': companyuser_id,
                    'coupon_channel': activity.coupon_channel
                }
                while True:
                    alidiscountcoupon_level = AliDiscountCouponLevel.objects.get(id=alidiscountcoupon_level_id)
                    instance_origin_take_number = alidiscountcoupon_level.take_number
                    instance_origin_receive_number = alidiscountcoupon_level.receive_number
                    instance_origin_remain_number = alidiscountcoupon_level.remain_number
                    instance_origin_p_take_number = alidiscountcoupon_level.p_take_number
                    instance_origin_p_receive_number = alidiscountcoupon_level.p_receive_number
                    instance_origin_p_remain_number = alidiscountcoupon_level.p_remain_number
                    instance_new_take_number = instance_origin_take_number + 1
                    instance_new_receive_number = instance_origin_receive_number + 1
                    instance_new_remain_number = instance_origin_remain_number - 1
                    instance_new_p_take_number = instance_origin_p_take_number + 1
                    instance_new_p_receive_number = instance_origin_p_receive_number + 1
                    instance_new_p_remain_number = instance_origin_p_remain_number - 1
                    result = AliDiscountCouponLevel.objects.filter(id=alidiscountcoupon_level_id, take_number=instance_origin_take_number).update(
                        take_number=instance_new_take_number,
                        receive_number=instance_new_receive_number,
                        remain_number=instance_new_remain_number,
                        p_take_number=instance_new_p_take_number,
                        p_receive_number=instance_new_p_receive_number,
                        p_remain_number=instance_new_p_remain_number
                    )
                    if result == 0:
                        continue
                    break
                while True:
                    activity = AliDiscountCoupon.objects.get(id=activity_id)
                    activity_origin_send_count = activity.send_count
                    activity_origin_remain_number = activity.remain_number
                    activity_new_send_count = activity_origin_send_count + 1
                    activity_new_remain_number = activity_origin_remain_number - 1
                    result = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
                        send_count=activity_new_send_count,
                        remain_number=activity_new_remain_number
                    )
                    if result == 0:
                        continue
                    break
                try:
                    relation_set = alidiscountcoupon_level.child_set.all()
                    for relation in relation_set:
                        parent = relation.parent
                        parent.p_take_number += 1
                        parent.p_receive_number += 1
                        parent.p_remain_number -= 1
                        parent.save()
                except:
                    pass
                voucherinfo, create = AliDiscountCouponInfo.objects.get_or_create(defaults=data, voucher_id=coupon_id)
                if create:
                    return Response({'success': '领取成功', 'coupon_id': voucherinfo.id}, status=status.HTTP_200_OK)
                else:
                    return Response({'error': '已经领取过了'}, status=status.HTTP_400_BAD_REQUEST)
            elif activity.coupon_channel == 5:
                meituan_result = favor_meituan_coupons(out_biz_no, activity.template_id, user.mobile)
                if meituan_result['out_biz_no'] != 'success':
                    if activity.coupon_way == 4:
                        while True:
                            activity = AliDiscountCoupon.objects.get(id=activity_id)
                            activity_origin_send_count = activity.send_count
                            activity_origin_remain_number = activity.remain_number
                            activity_new_send_count = activity_origin_send_count - 1
                            activity_new_remain_number = activity_origin_remain_number + 1
                            result1 = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
                                send_count=activity_new_send_count,
                                remain_number=activity_new_remain_number
                            )
                            if result1 == 0:
                                continue
                            break
                        while True:
                            alidiscountcoupon_level = AliDiscountCouponLevel.objects.get(id=alidiscountcoupon_level_id)
                            instance_origin_take_number = alidiscountcoupon_level.take_number
                            instance_origin_receive_number = alidiscountcoupon_level.receive_number
                            instance_origin_max_number = alidiscountcoupon_level.max_number
                            instance_origin_p_take_number = alidiscountcoupon_level.p_take_number
                            instance_origin_p_receive_number = alidiscountcoupon_level.p_receive_number
                            instance_origin_p_max_number = alidiscountcoupon_level.p_max_number
                            instance_new_take_number = instance_origin_take_number - 1
                            instance_new_receive_number = instance_origin_receive_number - 1
                            instance_new_max_number = instance_origin_max_number - 1
                            instance_new_p_take_number = instance_origin_p_take_number + 1
                            instance_new_p_receive_number = instance_origin_p_receive_number - 1
                            instance_new_p_max_number = instance_origin_p_max_number - 1
                            result1 = AliDiscountCouponLevel.objects.filter(id=alidiscountcoupon_level_id, take_number=instance_origin_take_number).update(
                                take_number=instance_new_take_number,
                                receive_number=instance_new_receive_number,
                                max_number=instance_new_max_number,
                                p_take_number=instance_new_p_take_number,
                                p_receive_number=instance_new_p_receive_number,
                                p_max_number=instance_new_p_max_number
                            )
                            if result1 == 0:
                                continue
                            break
                        try:
                            relation_set = alidiscountcoupon_level.child_set.all()
                            for relation in relation_set:
                                parent = relation.parent
                                parent.p_take_number -= 1
                                parent.p_receive_number -= 1
                                parent.p_max_number -= 1
                                parent.save()
                        except:
                            pass
                    else:
                        while True:
                            alidiscountcoupon_level = AliDiscountCouponLevel.objects.get(id=alidiscountcoupon_level_id)
                            instance_origin_take_number = alidiscountcoupon_level.take_number
                            instance_origin_receive_number = alidiscountcoupon_level.receive_number
                            instance_origin_remain_number = alidiscountcoupon_level.remain_number
                            instance_origin_p_take_number = alidiscountcoupon_level.p_take_number
                            instance_origin_p_receive_number = alidiscountcoupon_level.p_receive_number
                            instance_origin_p_remain_number = alidiscountcoupon_level.p_remain_number
                            instance_new_take_number = instance_origin_take_number - 1
                            instance_new_receive_number = instance_origin_receive_number - 1
                            instance_new_remain_number = instance_origin_remain_number + 1
                            instance_new_p_take_number = instance_origin_p_take_number - 1
                            instance_new_p_receive_number = instance_origin_p_receive_number - 1
                            instance_new_p_remain_number = instance_origin_p_remain_number + 1
                            result1 = AliDiscountCouponLevel.objects.filter(id=alidiscountcoupon_level_id, take_number=instance_origin_take_number).update(
                                take_number=instance_new_take_number,
                                receive_number=instance_new_receive_number,
                                remain_number=instance_new_remain_number,
                                p_take_number=instance_new_p_take_number,
                                p_receive_number=instance_new_p_receive_number,
                                p_remain_number=instance_new_p_remain_number
                            )
                            if result1 == 0:
                                continue
                            break
                        while True:
                            activity = AliDiscountCoupon.objects.get(id=activity_id)
                            activity_origin_send_count = activity.send_count
                            activity_origin_remain_number = activity.remain_number
                            activity_new_send_count = activity_origin_send_count - 1
                            activity_new_remain_number = activity_origin_remain_number + 1
                            result1 = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
                                send_count=activity_new_send_count,
                                remain_number=activity_new_remain_number
                            )
                            if result1 == 0:
                                continue
                            break
                        try:
                            relation_set = alidiscountcoupon_level.child_set.all()
                            for relation in relation_set:
                                parent = relation.parent
                                parent.p_take_number -= 1
                                parent.p_receive_number -= 1
                                parent.p_remain_number += 1
                                parent.save()
                        except:
                            pass
                    return Response({'error': meituan_result['errorMsg']}, status=status.HTTP_400_BAD_REQUEST)
                coupon_id = meituan_result['data'][0]['2023507366115002']
                user_id = user.mobile
                gmt_create = datetime.datetime.now()
                alidiscountcouponchannelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
                if alidiscountcouponchannelcommonvoucher.usetime_type == 2:
                    gmt_expired = alidiscountcouponchannelcommonvoucher.end_fixed_time
                    gmt_active = alidiscountcouponchannelcommonvoucher.start_fixed_time
                elif alidiscountcouponchannelcommonvoucher.usetime_type == 3:
                    gmt_expired = gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)
                    gmt_active = gmt_create
                else:
                    gmt_active = (gmt_create + datetime.timedelta(days=1)).strftime("%Y-%m-%d 00:00:00")
                    gmt_expired =(gmt_create+ datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)).strftime("%Y-%m-%d 23:59:59")
                data = {
                    'alidiscountcoupon_id': activity.id,
                    'voucher_id': coupon_id,
                    'user_id': user_id,
                    'template_id': activity.template_id,
                    'gmt_active': gmt_active,
                    'gmt_expired': gmt_expired,
                    'total_amount': activity.amount,
                    'gmt_create': gmt_create,
                    'available_amount': activity.amount,
                    'name': activity.activity_name,
                    'out_biz_no': out_biz_no,
                    'customer_user_id': user.id,
                    'alidiscountcoupon_level_id': alidiscountcoupon_level.id,
                    'level_id': alidiscountcoupon_level.level_id,
                    'mobile': user.mobile,
                    'coupon_channel': activity.coupon_channel
                }
                voucherinfo, create = AliDiscountCouponInfo.objects.get_or_create(defaults=data, out_biz_no=out_biz_no)
                if create:
                    return Response({'success': '领取成功', 'coupon_id': voucherinfo.id}, status=status.HTTP_200_OK)
                else:
                    return Response({'error': '已经领取过了'}, status=status.HTTP_400_BAD_REQUEST)
            else:
                voucher_id = f'{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}{random_str(14)}'
                user_id = user.ali_user_id
                gmt_create = datetime.datetime.now()
                alidiscountcouponchannelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
                if alidiscountcouponchannelcommonvoucher.usetime_type == 2:
                    gmt_expired = alidiscountcouponchannelcommonvoucher.end_fixed_time
                    gmt_active = alidiscountcouponchannelcommonvoucher.start_fixed_time
                elif alidiscountcouponchannelcommonvoucher.usetime_type == 3:
                    gmt_expired = gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)
                    gmt_active = gmt_create
                else:
                    gmt_active = (gmt_create + datetime.timedelta(days=1)).strftime("%Y-%m-%d 00:00:00")
                    gmt_expired =(gmt_create+ datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)).strftime("%Y-%m-%d 23:59:59")
                data = {
                    'alidiscountcoupon_id': activity.id,
                    'voucher_id': voucher_id,
                    'user_id': user_id,
                    'template_id': activity.template_id,
                    'gmt_active': gmt_active,
                    'gmt_expired': gmt_expired,
                    'total_amount': activity.amount,
                    'gmt_create': gmt_create,
                    'available_amount': activity.amount,
                    'name': activity.activity_name,
                    'out_biz_no': out_biz_no,
                    'customer_user_id': user.id,
                    'alidiscountcoupon_level_id': alidiscountcoupon_level.id,
                    'level_id': level_id,
                    'mobile': user.mobile,
                    'gmt_distributed': datetime.datetime.now(),
                    'companyuser_id': companyuser_id,
                    'coupon_channel': activity.coupon_channel
                }
                while True:
                    alidiscountcoupon_level = AliDiscountCouponLevel.objects.get(id=alidiscountcoupon_level_id)
                    instance_origin_take_number = alidiscountcoupon_level.take_number
                    instance_origin_receive_number = alidiscountcoupon_level.receive_number
                    instance_origin_remain_number = alidiscountcoupon_level.remain_number
                    instance_origin_p_take_number = alidiscountcoupon_level.p_take_number
                    instance_origin_p_receive_number = alidiscountcoupon_level.p_receive_number
                    instance_origin_p_remain_number = alidiscountcoupon_level.p_remain_number
                    instance_new_take_number = instance_origin_take_number + 1
                    instance_new_receive_number = instance_origin_receive_number + 1
                    instance_new_remain_number = instance_origin_remain_number - 1
                    instance_new_p_take_number = instance_origin_p_take_number + 1
                    instance_new_p_receive_number = instance_origin_p_receive_number + 1
                    instance_new_p_remain_number = instance_origin_p_remain_number - 1
                    result = AliDiscountCouponLevel.objects.filter(id=alidiscountcoupon_level_id, take_number=instance_origin_take_number).update(
                        take_number=instance_new_take_number,
                        receive_number=instance_new_receive_number,
                        remain_number=instance_new_remain_number,
                        p_take_number=instance_new_p_take_number,
                        p_receive_number=instance_new_p_receive_number,
                        p_remain_number=instance_new_p_remain_number
                    )
                    if result == 0:
                        continue
                    break
                while True:
                    activity = AliDiscountCoupon.objects.get(id=activity_id)
                    activity_origin_send_count = activity.send_count
                    activity_origin_remain_number = activity.remain_number
                    activity_new_send_count = activity_origin_send_count + 1
                    activity_new_remain_number = activity_origin_remain_number - 1
                    result = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
                        send_count=activity_new_send_count,
                        remain_number=activity_new_remain_number
                    )
                    if result == 0:
                        continue
                    break
                try:
                    relation_set = alidiscountcoupon_level.child_set.all()
                    for relation in relation_set:
                        parent = relation.parent
                        parent.p_take_number += 1
                        parent.p_receive_number += 1
                        parent.p_remain_number -= 1
                        parent.save()
                except:
                    pass
                voucherinfo, create = AliDiscountCouponInfo.objects.get_or_create(defaults=data, voucher_id=voucher_id)
                if create:
                    return Response({'success': '领取成功', 'coupon_id': voucherinfo.id}, status=status.HTTP_200_OK)
                else:
                    return Response({'error': '已经领取过了'}, status=status.HTTP_400_BAD_REQUEST)
        elif len(identify) == 64:
            today = datetime.datetime.now()
            try:
                alidiscountcoupon_level = AliDiscountCouponLevel.objects.get(identify=identify)
            except:
                return Response({'error': '无效二维码,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
            activity = alidiscountcoupon_level.activity
            if activity.publish_start_time > today:
                return Response({'error': '活动尚未开始'}, status=status.HTTP_400_BAD_REQUEST)
            if activity.publish_end_time < today:
                return Response({'error': '活动尚已结束'}, status=status.HTTP_400_BAD_REQUEST)
            if activity.coupon_channel != 5:
                out_biz_no = f'100004{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
            else:
                out_biz_no = f'{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}{"%04d" % randint(0, 9999)}'
            try:
                channelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
                if channelcommonvoucher.distributed_limit_by_time == 1:
                    week = str(datetime.datetime.now().weekday())
                    enable_time = datetime.datetime.now().strftime('1970-01-01 %H:%M:%S')
                    alidiscountcoupondstributedlimit = AliDiscountCouponDistributedLimit.objects.filter(ali_discount_coupon_common_voucher_id=channelcommonvoucher.id, weeks__contains=week, start_enable_time__lte=enable_time, end_enable_time__gte=enable_time)
                    if not alidiscountcoupondstributedlimit:
                        return Response({'error': '没到活动派发时间'}, status=status.HTTP_400_BAD_REQUEST)
                if channelcommonvoucher.join_limit_by_location == 1:
                    if not all([latitude, longitude]):
                        return Response({'error': '请开启位置定位信息'}, status=status.HTTP_400_BAD_REQUEST)
                    check_location = AliDiscountCouponJoinLimitLocation.objects.filter(
                        longitude_begin__lte=longitude,
                        longitude_end__gte=longitude,
                        latitude_begin__lte=latitude,
                        latitude_end__gte=latitude,
                        ali_discount_coupon_common_voucher_id=channelcommonvoucher.id
                    )
                    if not check_location:
                        return Response({'error': '当前区域不支持参与该活动'}, status=status.HTTP_400_BAD_REQUEST)
            except:
                pass
            if activity.is_white:
                is_white = AliDiscountCouponWhiteTable.objects.filter(mobile=user.mobile, alidiscountcoupon_id=activity.id)
                if not is_white:
                    return Response({'error': '您没有该优惠券领取权限，请联系客户经理参与活动。'}, status=status.HTTP_400_BAD_REQUEST)
            if activity.is_check_identity == 1:
                check_manager = User.objects.filter(mobile=user.mobile, is_active=1)
                if check_manager:
                    return Response({'error': '该活动暂不允许内部员工领取，如有疑问请咨询客服。'}, status=status.HTTP_400_BAD_REQUEST)
            if user.is_auth != 2 and activity.is_need_auth == 1:
                return Response({'error': '请先完成实名认证'}, status=status.HTTP_400_BAD_REQUEST)
            if activity.max_number_by_day:
                begin_time = datetime.datetime.now().strftime('%Y-%m-%d 00:00:00')
                end_time = datetime.datetime.now().strftime('%Y-%m-%d 23:59:59')
                max_no = AliDiscountCouponInfo.objects.filter(alidiscountcoupon_id=activity.id, gmt_create__gte=begin_time,gmt_create__lte=end_time).count()
                if max_no >= activity.max_number_by_day:
                    return Response({'error': '今天的优惠券已领取完毕，请明天0点继续参与，感谢您对本活动的支持！'}, status=status.HTTP_400_BAD_REQUEST)
            if activity.max_number_by_user:
                max_no = AliDiscountCouponInfo.objects.filter(alidiscountcoupon_id=activity.id, customer_user_id=user.id).count()
                if max_no >= activity.max_number_by_user:
                    return Response({'error': '用户参与活动次数已达上限，感谢您对本活动的支持！'}, status=status.HTTP_400_BAD_REQUEST)
            if activity.coupon_way == 2:
                if alidiscountcoupon_level.remain_number <= 0:
                    return Response({'error': '活动已达到派发上限'}, status=status.HTTP_400_BAD_REQUEST)
                alidiscountcoupon_level_id = alidiscountcoupon_level.id
                activity_id = activity.id
                template_id = activity.template_id
                user_id = user.ali_user_id
                if activity.coupon_channel == 1:
                    alipay_obj = AlipayOpen()
                    if not login_id:
                        if not user.ali_user_id:
                            return Response({'error': '用户尚未关联支付宝,请使用支付宝扫码领取'}, status=status.HTTP_400_BAD_REQUEST)
                        if activity.coupon_type == 11:
                            result = json.loads(alipay_obj.campaign_drawcamp_trigger_user_id(user_id, template_id, out_biz_no))
                        else:
                            result = json.loads(alipay_obj.vouchersend(user_id, template_id, out_biz_no))
                    else:
                        if activity.coupon_type == 11:
                            result = json.loads(alipay_obj.campaign_drawcamp_trigger_login_id(login_id, template_id, out_biz_no))
                        else:
                            result = json.loads(alipay_obj.vouchersend_login_id(login_id, template_id, out_biz_no))
                    if result['code'] != '10000':
                        logger.error(str(result))
                        try:
                            return Response({'error': result['sub_msg']}, status=status.HTTP_400_BAD_REQUEST)
                        except:
                            return Response({'error': '领取失败,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
                    if activity.coupon_type == 11:
                        if not result['trigger_result']:
                            try:
                                return Response({'error': json.loads(result['extend_field'])['errorMsg'], 'status': 0}, status=status.HTTP_400_BAD_REQUEST)
                            except:
                                return Response({'error': '领取失败,请联系管理员', 'status': 0}, status=status.HTTP_400_BAD_REQUEST)
                        voucher_id = result['out_prize_id']
                    else:
                        voucher_id = result['voucher_id']
                    if activity.platform_id == 1:
                        result = json.loads(alipay_obj.voucherquery(voucher_id))
                        data = {
                            'alidiscountcoupon_id': activity.id,
                            'voucher_id': voucher_id,
                            'user_id': user_id,
                            'template_id': result['template_id'],
                            'gmt_active': result['gmt_active'],
                            'gmt_expired': result['gmt_expired'],
                            'total_amount': result['total_amount'],
                            'gmt_create': result['gmt_create'],
                            'available_amount': result['available_amount'],
                            'name': result['name'],
                            'out_biz_no': out_biz_no,
                            'customer_user_id': user.id,
                            'gmt_distributed': datetime.datetime.now(),
                            'alidiscountcoupon_level_id': alidiscountcoupon_level.id,
                            'level_id': alidiscountcoupon_level.level_id,
                            'mobile': user.mobile,
                            'coupon_channel': activity.coupon_channel,
                            'login_id': login_id
                        }
                    else:
                        gmt_create = datetime.datetime.now()
                        alidiscountcouponchannelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
                        if alidiscountcouponchannelcommonvoucher.usetime_type == 2:
                            gmt_expired = alidiscountcouponchannelcommonvoucher.end_fixed_time
                            gmt_active = alidiscountcouponchannelcommonvoucher.start_fixed_time
                        elif alidiscountcouponchannelcommonvoucher.usetime_type == 3:
                            gmt_expired = gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)
                            gmt_active = gmt_create
                        else:
                            gmt_active = (gmt_create + datetime.timedelta(days=1)).strftime("%Y-%m-%d 00:00:00")
                            gmt_expired = (gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)).strftime("%Y-%m-%d 23:59:59")
                        data = {
                            'alidiscountcoupon_id': activity.id,
                            'voucher_id': voucher_id,
                            'user_id': user_id,
                            'template_id': activity.template_id,
                            'gmt_active': gmt_active,
                            'gmt_expired': gmt_expired,
                            'total_amount': activity.amount,
                            'gmt_create': gmt_create,
                            'available_amount': activity.amount,
                            'name': activity.activity_name,
                            'out_biz_no': out_biz_no,
                            'customer_user_id': user.id,
                            'gmt_distributed': gmt_create,
                            'alidiscountcoupon_level_id': alidiscountcoupon_level.id,
                            'level_id': alidiscountcoupon_level.level_id,
                            'mobile': user.mobile,
                            'coupon_channel': activity.coupon_channel,
                            'login_id': login_id
                        }
                    voucherinfo, create = AliDiscountCouponInfo.objects.get_or_create(defaults=data, voucher_id=voucher_id)
                    while True:
                        alidiscountcoupon_level = AliDiscountCouponLevel.objects.get(id=alidiscountcoupon_level_id)
                        instance_origin_take_number = alidiscountcoupon_level.take_number
                        instance_origin_receive_number = alidiscountcoupon_level.receive_number
                        instance_origin_remain_number = alidiscountcoupon_level.remain_number
                        instance_origin_p_take_number = alidiscountcoupon_level.p_take_number
                        instance_origin_p_receive_number = alidiscountcoupon_level.p_receive_number
                        instance_origin_p_remain_number = alidiscountcoupon_level.p_remain_number
                        instance_new_take_number = instance_origin_take_number + 1
                        instance_new_receive_number = instance_origin_receive_number + 1
                        instance_new_remain_number = instance_origin_remain_number + 1
                        instance_new_p_take_number = instance_origin_p_take_number + 1
                        instance_new_p_receive_number = instance_origin_p_receive_number + 1
                        instance_new_p_remain_number = instance_origin_p_remain_number + 1
                        result = AliDiscountCouponLevel.objects.filter(id=alidiscountcoupon_level_id, take_number=instance_origin_take_number).update(
                            take_number=instance_new_take_number,
                            receive_number=instance_new_receive_number,
                            remain_number=instance_new_remain_number,
                            p_take_number=instance_new_p_take_number,
                            p_receive_number=instance_new_p_receive_number,
                            p_remain_number=instance_new_p_remain_number
                        )
                        if result == 0:
                            continue
                        break
                    while True:
                        activity = AliDiscountCoupon.objects.get(id=activity_id)
                        activity_origin_send_count = activity.send_count
                        activity_origin_remain_number = activity.remain_number
                        activity_new_send_count = activity_origin_send_count + 1
                        activity_new_remain_number = activity_origin_remain_number - 1
                        result = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
                            send_count=activity_new_send_count,
                            remain_number=activity_new_remain_number
                        )
                        if result == 0:
                            continue
                        break
                    try:
                        relation_set = alidiscountcoupon_level.child_set.all()
                        for relation in relation_set:
                            parent = relation.parent
                            parent.p_take_number += 1
                            parent.p_receive_number += 1
                            parent.p_remain_number -= 1
                            parent.save()
                    except:
                        pass
                    if create:
                        return Response({'success': '领取成功', 'coupon_id': voucherinfo.id}, status=status.HTTP_200_OK)
                    else:
                        return Response({'error': '已经领取过了'}, status=status.HTTP_400_BAD_REQUEST)
                elif activity.coupon_channel == 2:
                    if user.new_openid:
                        appid = settings.CUSTOMER_APP_ID_NEW
                        openid = user.new_openid
                    elif user.openid:
                        appid = settings.CUSTOMER_APP_ID
                        openid = user.openid
                    else:
                        return Response({'error': '用户尚未关联微信,请使用微信【赋有】小程序授权登录'}, status=status.HTTP_400_BAD_REQUEST)
                    if activity.platform_id == 13:
                        distribute_channel = Channel.objects.get(id=13)
                    else:
                        distribute_channel = Channel.objects.get(id=9)
                    data_json = {
                        "stock_id": activity.template_id,
                        "out_request_no": out_biz_no,
                        "appid": appid,
                        "stock_creator_mchid": activity.platform.mchid
                    }
                    data_dict = favor_distributed_coupons_sichun(data_json, openid, distribute_channel)
                    if 'code' in data_dict:
                        return Response({'error': data_dict['message']}, status=status.HTTP_400_BAD_REQUEST)
                    coupon_id = data_dict['coupon_id']
                    result = favor_query_coupons_sichun(coupon_id, openid, appid, distribute_channel)
                    data = {
                        'alidiscountcoupon_id': activity.id,
                        'voucher_id': coupon_id,
                        'user_id': openid,
                        'template_id': result['stock_id'],
                        'gmt_active': result['available_begin_time'].replace('T', ' ').replace('+08:00', ''),
                        'gmt_expired': result['available_end_time'].replace('T', ' ').replace('+08:00', ''),
                        'total_amount': result['normal_coupon_information']['coupon_amount']/100,
                        'gmt_create': datetime.datetime.now(),
                        'available_amount': result['normal_coupon_information']['coupon_amount']/100,
                        'name': result['coupon_name'],
                        'out_biz_no': out_biz_no,
                        'customer_user_id': user.id,
                        'gmt_distributed': datetime.datetime.now(),
                        'alidiscountcoupon_level_id': alidiscountcoupon_level.id,
                        'level_id': alidiscountcoupon_level.level_id,
                        'mobile': user.mobile,
                        'coupon_channel': activity.coupon_channel
                    }
                    voucherinfo, create = AliDiscountCouponInfo.objects.get_or_create(defaults=data, voucher_id=coupon_id)
                    if create:
                        return Response({'success': '领取成功', 'coupon_id': voucherinfo.id}, status=status.HTTP_200_OK)
                    else:
                        return Response({'error': '已经领取过了'}, status=status.HTTP_400_BAD_REQUEST)
                elif activity.coupon_channel == 5:
                    meituan_result = favor_meituan_coupons(out_biz_no, activity.template_id, user.mobile)
                    if meituan_result['status'] != 'success':
                        return Response({'error': meituan_result['errorMsg']}, status=status.HTTP_400_BAD_REQUEST)
                    coupon_id = meituan_result['data'][0]['code']
                    user_id = user.mobile
                    gmt_create = datetime.datetime.now()
                    alidiscountcouponchannelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
                    if alidiscountcouponchannelcommonvoucher.usetime_type == 2:
                        gmt_expired = alidiscountcouponchannelcommonvoucher.end_fixed_time
                        gmt_active = alidiscountcouponchannelcommonvoucher.start_fixed_time
                    elif alidiscountcouponchannelcommonvoucher.usetime_type == 3:
                        gmt_expired = gmt_create + datetime.timedelta(
                            days=alidiscountcouponchannelcommonvoucher.invalid_day)
                        gmt_active = gmt_create
                    else:
                        gmt_active = (gmt_create + datetime.timedelta(days=1)).strftime("%Y-%m-%d 00:00:00")
                        gmt_expired = (gmt_create + datetime.timedelta(
                            days=alidiscountcouponchannelcommonvoucher.invalid_day)).strftime("%Y-%m-%d 23:59:59")
                    data = {
                        'alidiscountcoupon_id': activity.id,
                        'voucher_id': coupon_id,
                        'user_id': user_id,
                        'template_id': activity.template_id,
                        'gmt_active': gmt_active,
                        'gmt_expired': gmt_expired,
                        'total_amount': activity.amount,
                        'gmt_create': gmt_create,
                        'available_amount': activity.amount,
                        'name': activity.activity_name,
                        'out_biz_no': out_biz_no,
                        'customer_user_id': user.id,
                        'alidiscountcoupon_level_id': alidiscountcoupon_level.id,
                        'level_id': alidiscountcoupon_level.level_id,
                        'mobile': user.mobile,
                        'coupon_channel': activity.coupon_channel
                    }
                    voucherinfo, create = AliDiscountCouponInfo.objects.get_or_create(defaults=data, out_biz_no=out_biz_no)
                    if create:
                        while True:
                            alidiscountcoupon_level = AliDiscountCouponLevel.objects.get(id=alidiscountcoupon_level_id)
                            instance_origin_take_number = alidiscountcoupon_level.take_number
                            instance_origin_receive_number = alidiscountcoupon_level.receive_number
                            instance_origin_remain_number = alidiscountcoupon_level.remain_number
                            instance_origin_p_take_number = alidiscountcoupon_level.p_take_number
                            instance_origin_p_receive_number = alidiscountcoupon_level.p_receive_number
                            instance_origin_p_remain_number = alidiscountcoupon_level.p_remain_number
                            instance_new_take_number = instance_origin_take_number + 1
                            instance_new_receive_number = instance_origin_receive_number + 1
                            instance_new_remain_number = instance_origin_remain_number - 1
                            instance_new_p_take_number = instance_origin_p_take_number + 1
                            instance_new_p_receive_number = instance_origin_p_receive_number + 1
                            instance_new_p_remain_number = instance_origin_p_remain_number - 1
                            result = AliDiscountCouponLevel.objects.filter(id=alidiscountcoupon_level_id,
                                                                           take_number=instance_origin_take_number).update(
                                take_number=instance_new_take_number,
                                receive_number=instance_new_receive_number,
                                remain_number=instance_new_remain_number,
                                p_take_number=instance_new_p_take_number,
                                p_receive_number=instance_new_p_receive_number,
                                p_remain_number=instance_new_p_remain_number
                            )
                            if result == 0:
                                continue
                            break
                        while True:
                            activity = AliDiscountCoupon.objects.get(id=activity_id)
                            activity_origin_send_count = activity.send_count
                            activity_origin_remain_number = activity.remain_number
                            activity_new_send_count = activity_origin_send_count + 1
                            activity_new_remain_number = activity_origin_remain_number - 1
                            result = AliDiscountCoupon.objects.filter(id=activity_id,
                                                                      send_count=activity_origin_send_count).update(
                                send_count=activity_new_send_count,
                                remain_number=activity_new_remain_number
                            )
                            if result == 0:
                                continue
                            break
                        try:
                            relation_set = alidiscountcoupon_level.child_set.all()
                            for relation in relation_set:
                                parent = relation.parent
                                parent.p_take_number += 1
                                parent.p_receive_number += 1
                                parent.p_remain_number -= 1
                                parent.save()
                        except:
                            pass
                        return Response({'success': '领取成功', 'coupon_id': voucherinfo.id}, status=status.HTTP_200_OK)
                    else:
                        return Response({'error': '已经领取过了'}, status=status.HTTP_400_BAD_REQUEST)
                else:
                    voucher_id = f'{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}{random_str(14)}'
                    user_id = user.ali_user_id
                    gmt_create = datetime.datetime.now()
                    alidiscountcouponchannelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
                    if alidiscountcouponchannelcommonvoucher.usetime_type == 2:
                        gmt_expired = alidiscountcouponchannelcommonvoucher.end_fixed_time
                        gmt_active = alidiscountcouponchannelcommonvoucher.start_fixed_time
                    elif alidiscountcouponchannelcommonvoucher.usetime_type == 3:
                        gmt_expired = gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)
                        gmt_active = gmt_create
                    else:
                        gmt_active = (gmt_create + datetime.timedelta(days=1)).strftime("%Y-%m-%d 00:00:00")
                        gmt_expired =(gmt_create+ datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)).strftime("%Y-%m-%d 23:59:59")
                    data = {
                        'alidiscountcoupon_id': activity.id,
                        'voucher_id': voucher_id,
                        'user_id': user_id,
                        'template_id': activity.template_id,
                        'gmt_active': gmt_active,
                        'gmt_expired': gmt_expired,
                        'total_amount': activity.amount,
                        'gmt_create': gmt_create,
                        'available_amount': activity.amount,
                        'name': activity.activity_name,
                        'out_biz_no': out_biz_no,
                        'customer_user_id': user.id,
                        'alidiscountcoupon_level_id': alidiscountcoupon_level.id,
                        'level_id': alidiscountcoupon_level.level_id,
                        'mobile': user.mobile,
                        'gmt_distributed': datetime.datetime.now(),
                        'coupon_channel': activity.coupon_channel
                    }
                    while True:
                        alidiscountcoupon_level = AliDiscountCouponLevel.objects.get(id=alidiscountcoupon_level_id)
                        instance_origin_take_number = alidiscountcoupon_level.take_number
                        instance_origin_receive_number = alidiscountcoupon_level.receive_number
                        instance_origin_remain_number = alidiscountcoupon_level.remain_number
                        instance_origin_p_take_number = alidiscountcoupon_level.p_take_number
                        instance_origin_p_receive_number = alidiscountcoupon_level.p_receive_number
                        instance_origin_p_remain_number = alidiscountcoupon_level.p_remain_number
                        instance_new_take_number = instance_origin_take_number + 1
                        instance_new_receive_number = instance_origin_receive_number + 1
                        instance_new_remain_number = instance_origin_remain_number - 1
                        instance_new_p_take_number = instance_origin_p_take_number + 1
                        instance_new_p_receive_number = instance_origin_p_receive_number + 1
                        instance_new_p_remain_number = instance_origin_p_remain_number - 1
                        result = AliDiscountCouponLevel.objects.filter(id=alidiscountcoupon_level_id, take_number=instance_origin_take_number).update(
                            take_number=instance_new_take_number,
                            receive_number=instance_new_receive_number,
                            remain_number=instance_new_remain_number,
                            p_take_number=instance_new_p_take_number,
                            p_receive_number=instance_new_p_receive_number,
                            p_remain_number=instance_new_p_remain_number
                        )
                        if result == 0:
                            continue
                        break
                    while True:
                        activity = AliDiscountCoupon.objects.get(id=activity_id)
                        activity_origin_send_count = activity.send_count
                        activity_origin_remain_number = activity.remain_number
                        activity_new_send_count = activity_origin_send_count + 1
                        activity_new_remain_number = activity_origin_remain_number - 1
                        result = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
                            send_count=activity_new_send_count,
                            remain_number=activity_new_remain_number
                        )
                        if result == 0:
                            continue
                        break
                    try:
                        relation_set = alidiscountcoupon_level.child_set.all()
                        for relation in relation_set:
                            parent = relation.parent
                            parent.p_take_number += 1
                            parent.p_receive_number += 1
                            parent.p_remain_number -= 1
                            parent.save()
                    except:
                        pass
                    voucherinfo, create = AliDiscountCouponInfo.objects.get_or_create(defaults=data, voucher_id=voucher_id)
                    if create:
                        return Response({'success': '领取成功', 'coupon_id': voucherinfo.id}, status=status.HTTP_200_OK)
                    else:
                        return Response({'error': '已经领取过了'}, status=status.HTTP_400_BAD_REQUEST)
            else:
                if activity.remain_number <= 0:
                    return Response({'error': '活动已达到派发上限'}, status=status.HTTP_400_BAD_REQUEST)
                alidiscountcoupon_level_id = alidiscountcoupon_level.id
                activity_id = activity.id
                template_id = activity.template_id
                user_id = user.ali_user_id
                if activity.coupon_channel == 1:
                    alipay_obj = AlipayOpen()
                    if not login_id:
                        if not user.ali_user_id:
                            return Response({'error': '用户尚未关联支付宝,请使用支付宝扫码领取'}, status=status.HTTP_400_BAD_REQUEST)
                        if activity.coupon_type == 11:
                            result = json.loads(alipay_obj.campaign_drawcamp_trigger_user_id(user_id, template_id, out_biz_no))
                        else:
                            result = json.loads(alipay_obj.vouchersend(user_id, template_id, out_biz_no))
                    else:
                        if activity.coupon_type == 11:
                            result = json.loads(alipay_obj.campaign_drawcamp_trigger_login_id(login_id, template_id, out_biz_no))
                        else:
                            result = json.loads(alipay_obj.vouchersend_login_id(login_id, template_id, out_biz_no))
                    if result['code'] != '10000':
                        logger.error(str(result))
                        try:
                            return Response({'error': result['sub_msg']}, status=status.HTTP_400_BAD_REQUEST)
                        except:
                            return Response({'error': '领取失败,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
                    if activity.coupon_type == 11:
                        if not result['trigger_result']:
                            try:
                                return Response({'error': json.loads(result['extend_field'])['errorMsg'], 'status': 0}, status=status.HTTP_400_BAD_REQUEST)
                            except:
                                return Response({'error': '领取失败,请联系管理员', 'status': 0}, status=status.HTTP_400_BAD_REQUEST)
                        voucher_id = result['out_prize_id']
                    else:
                        voucher_id = result['voucher_id']
                    # alipay_obj = AlipayOpen()
                    # user_id = user.ali_user_id
                    # template_id = activity.template_id
                    # result = json.loads(alipay_obj.vouchersend(user_id, template_id, out_biz_no))
                    # if result['code'] != '10000':
                    #     logger.error(str(result))
                    #     try:
                    #         return Response({'error': result['sub_msg']}, status=status.HTTP_400_BAD_REQUEST)
                    #     except:
                    #         return Response({'error': '领取失败,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
                    # voucher_id = result['voucher_id']
                    if activity.platform_id == 1:
                        result = json.loads(alipay_obj.voucherquery(voucher_id))
                        data = {
                            'alidiscountcoupon_id': activity.id,
                            'voucher_id': voucher_id,
                            'user_id': user_id,
                            'template_id': result['template_id'],
                            'gmt_active': result['gmt_active'],
                            'gmt_expired': result['gmt_expired'],
                            'total_amount': result['total_amount'],
                            'gmt_create': result['gmt_create'],
                            'available_amount': result['available_amount'],
                            'name': result['name'],
                            'out_biz_no': out_biz_no,
                            'customer_user_id': user.id,
                            'gmt_distributed': datetime.datetime.now(),
                            'alidiscountcoupon_level_id': alidiscountcoupon_level.id,
                            'level_id': alidiscountcoupon_level.level_id,
                            'mobile': user.mobile,
                            'coupon_channel': activity.coupon_channel,
                            'login_id': login_id
                        }
                    else:
                        gmt_create = datetime.datetime.now()
                        alidiscountcouponchannelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
                        if alidiscountcouponchannelcommonvoucher.usetime_type == 2:
                            gmt_expired = alidiscountcouponchannelcommonvoucher.end_fixed_time
                            gmt_active = alidiscountcouponchannelcommonvoucher.start_fixed_time
                        elif alidiscountcouponchannelcommonvoucher.usetime_type == 3:
                            gmt_expired = gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)
                            gmt_active = gmt_create
                        else:
                            gmt_active = (gmt_create + datetime.timedelta(days=1)).strftime("%Y-%m-%d 00:00:00")
                            gmt_expired = (gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)).strftime("%Y-%m-%d 23:59:59")
                        data = {
                            'alidiscountcoupon_id': activity.id,
                            'voucher_id': voucher_id,
                            'user_id': user_id,
                            'template_id': activity.template_id,
                            'gmt_active': gmt_active,
                            'gmt_expired': gmt_expired,
                            'total_amount': activity.amount,
                            'gmt_create': gmt_create,
                            'available_amount': activity.amount,
                            'name': activity.activity_name,
                            'out_biz_no': out_biz_no,
                            'customer_user_id': user.id,
                            'gmt_distributed': gmt_create,
                            'alidiscountcoupon_level_id': alidiscountcoupon_level.id,
                            'level_id': alidiscountcoupon_level.level_id,
                            'mobile': user.mobile,
                            'coupon_channel': activity.coupon_channel,
                            'login_id': login_id
                        }
                    voucherinfo, create = AliDiscountCouponInfo.objects.get_or_create(defaults=data, voucher_id=voucher_id)
                    while True:
                        activity = AliDiscountCoupon.objects.get(id=activity_id)
                        activity_origin_send_count = activity.send_count
                        activity_origin_remain_number = activity.remain_number
                        activity_new_send_count = activity_origin_send_count + 1
                        activity_new_remain_number = activity_origin_remain_number - 1
                        result = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(send_count=activity_new_send_count, remain_number=activity_new_remain_number)
                        if result == 0:
                            continue
                        break
                    while True:
                        alidiscountcoupon_level = AliDiscountCouponLevel.objects.get(id=alidiscountcoupon_level_id)
                        instance_origin_take_number = alidiscountcoupon_level.take_number
                        instance_origin_receive_number = alidiscountcoupon_level.receive_number
                        instance_origin_max_number = alidiscountcoupon_level.max_number
                        instance_origin_p_take_number = alidiscountcoupon_level.p_take_number
                        instance_origin_p_receive_number = alidiscountcoupon_level.p_receive_number
                        instance_origin_p_max_number = alidiscountcoupon_level.p_max_number
                        instance_new_take_number = instance_origin_take_number + 1
                        instance_new_receive_number = instance_origin_receive_number + 1
                        instance_new_max_number = instance_origin_max_number + 1
                        instance_new_p_take_number = instance_origin_p_take_number + 1
                        instance_new_p_receive_number = instance_origin_p_receive_number + 1
                        instance_new_p_max_number = instance_origin_p_max_number + 1
                        result = AliDiscountCouponLevel.objects.filter(id=alidiscountcoupon_level_id, take_number=instance_origin_take_number).update(
                            take_number=instance_new_take_number,
                            receive_number=instance_new_receive_number,
                            max_number=instance_new_max_number,
                            p_take_number=instance_new_p_take_number,
                            p_receive_number=instance_new_p_receive_number,
                            p_max_number=instance_new_p_max_number
                        )
                        if result == 0:
                            continue
                        break
                    try:
                        relation_set = alidiscountcoupon_level.child_set.all()
                        for relation in relation_set:
                            parent = relation.parent
                            parent.p_take_number += 1
                            parent.p_receive_number += 1
                            parent.p_max_number += 1
                            parent.save()
                    except:
                        pass
                    if create:
                        return Response({'success': '领取成功', 'coupon_id': voucherinfo.id}, status=status.HTTP_200_OK)
                    else:
                        return Response({'error': '已经领取过了'}, status=status.HTTP_400_BAD_REQUEST)
                elif activity.coupon_channel == 2:
                    if user.new_openid:
                        appid = settings.CUSTOMER_APP_ID_NEW
                        openid = user.new_openid
                    elif user.openid:
                        appid = settings.CUSTOMER_APP_ID
                        openid = user.openid
                    else:
                        return Response({'error': '用户尚未关联微信,请使用微信【赋有】小程序授权登录'}, status=status.HTTP_400_BAD_REQUEST)
                    while True:
                        activity = AliDiscountCoupon.objects.get(id=activity_id)
                        if activity.remain_number <= 0:
                            return Response({'error': '活动已达到派发上限'}, status=status.HTTP_400_BAD_REQUEST)
                        activity_origin_send_count = activity.send_count
                        activity_origin_remain_number = activity.remain_number
                        activity_new_send_count = activity_origin_send_count + 1
                        activity_new_remain_number = activity_origin_remain_number - 1
                        result = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(send_count=activity_new_send_count, remain_number=activity_new_remain_number)
                        if result == 0:
                            continue
                        break
                    if activity.platform_id == 13:
                        distribute_channel = Channel.objects.get(id=13)
                    else:
                        distribute_channel = Channel.objects.get(id=9)
                    data_json = {
                        "stock_id": activity.template_id,
                        "out_request_no": out_biz_no,
                        "appid": appid,
                        "stock_creator_mchid": activity.platform.mchid
                    }
                    data_dict = favor_distributed_coupons_sichun(data_json, openid, distribute_channel)
                    if 'code' in data_dict:
                        while True:
                            activity = AliDiscountCoupon.objects.get(id=activity_id)
                            activity_origin_send_count = activity.send_count
                            activity_origin_remain_number = activity.remain_number
                            activity_new_send_count = activity_origin_send_count - 1
                            activity_new_remain_number = activity_origin_remain_number + 1
                            result = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(send_count=activity_new_send_count, remain_number=activity_new_remain_number)
                            if result == 0:
                                continue
                            break
                        return Response({'error': data_dict['message']}, status=status.HTTP_400_BAD_REQUEST)
                    coupon_id = data_dict['coupon_id']
                    result = favor_query_coupons_sichun(coupon_id, openid, appid, distribute_channel)
                    data = {
                        'alidiscountcoupon_id': activity.id,
                        'voucher_id': coupon_id,
                        'user_id': openid,
                        'template_id': result['stock_id'],
                        'gmt_active': result['available_begin_time'].replace('T', ' ').replace('+08:00', ''),
                        'gmt_expired': result['available_end_time'].replace('T', ' ').replace('+08:00', ''),
                        'total_amount': result['normal_coupon_information']['coupon_amount']/100,
                        'gmt_create': datetime.datetime.now(),
                        'available_amount': result['normal_coupon_information']['coupon_amount']/100,
                        'name': result['coupon_name'],
                        'out_biz_no': out_biz_no,
                        'customer_user_id': user.id,
                        'gmt_distributed': datetime.datetime.now(),
                        'alidiscountcoupon_level_id': alidiscountcoupon_level.id,
                        'level_id': alidiscountcoupon_level.level_id,
                        'mobile': user.mobile,
                        'coupon_channel': activity.coupon_channel
                    }
                    while True:
                        alidiscountcoupon_level = AliDiscountCouponLevel.objects.get(id=alidiscountcoupon_level_id)
                        instance_origin_take_number = alidiscountcoupon_level.take_number
                        instance_origin_receive_number = alidiscountcoupon_level.receive_number
                        instance_origin_max_number = alidiscountcoupon_level.max_number
                        instance_origin_p_take_number = alidiscountcoupon_level.p_take_number
                        instance_origin_p_receive_number = alidiscountcoupon_level.p_receive_number
                        instance_origin_p_max_number = alidiscountcoupon_level.p_max_number
                        instance_new_take_number = instance_origin_take_number + 1
                        instance_new_receive_number = instance_origin_receive_number + 1
                        instance_new_max_number = instance_origin_max_number + 1
                        instance_new_p_take_number = instance_origin_p_take_number + 1
                        instance_new_p_receive_number = instance_origin_p_receive_number + 1
                        instance_new_p_max_number = instance_origin_p_max_number + 1
                        result = AliDiscountCouponLevel.objects.filter(id=alidiscountcoupon_level_id, take_number=instance_origin_take_number).update(
                            take_number=instance_new_take_number,
                            receive_number=instance_new_receive_number,
                            max_number=instance_new_max_number,
                            p_take_number=instance_new_p_take_number,
                            p_receive_number=instance_new_p_receive_number,
                            p_max_number=instance_new_p_max_number
                        )
                        if result == 0:
                            continue
                        break
                    try:
                        relation_set = alidiscountcoupon_level.child_set.all()
                        for relation in relation_set:
                            parent = relation.parent
                            parent.p_take_number += 1
                            parent.p_receive_number += 1
                            parent.p_max_number += 1
                            parent.save()
                    except:
                        pass
                    voucherinfo, create = AliDiscountCouponInfo.objects.get_or_create(defaults=data, voucher_id=coupon_id)
                    if create:
                        return Response({'success': '领取成功', 'coupon_id': voucherinfo.id}, status=status.HTTP_200_OK)
                    else:
                        return Response({'error': '已经领取过了'}, status=status.HTTP_400_BAD_REQUEST)
                elif activity.coupon_channel == 5:
                    while True:
                        activity = AliDiscountCoupon.objects.get(id=activity_id)
                        if activity.remain_number <= 0:
                            return Response({'error': '活动已达到派发上限'}, status=status.HTTP_400_BAD_REQUEST)
                        activity_origin_send_count = activity.send_count
                        activity_origin_remain_number = activity.remain_number
                        activity_new_send_count = activity_origin_send_count + 1
                        activity_new_remain_number = activity_origin_remain_number - 1
                        result = AliDiscountCoupon.objects.filter(id=activity_id,send_count=activity_origin_send_count).update(send_count=activity_new_send_count, remain_number=activity_new_remain_number)
                        if result == 0:
                            continue
                        break
                    meituan_result = favor_meituan_coupons(out_biz_no, activity.template_id, user.mobile)
                    if meituan_result['status'] != 'success':
                        while True:
                            activity = AliDiscountCoupon.objects.get(id=activity_id)
                            activity_origin_send_count = activity.send_count
                            activity_origin_remain_number = activity.remain_number
                            activity_new_send_count = activity_origin_send_count - 1
                            activity_new_remain_number = activity_origin_remain_number + 1
                            result = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(send_count=activity_new_send_count, remain_number=activity_new_remain_number)
                            if result == 0:
                                continue
                            break
                        return Response({'error': meituan_result['errorMsg']}, status=status.HTTP_400_BAD_REQUEST)
                    coupon_id = meituan_result['data'][0]['code']
                    user_id = user.mobile
                    gmt_create = datetime.datetime.now()
                    alidiscountcouponchannelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
                    if alidiscountcouponchannelcommonvoucher.usetime_type == 2:
                        gmt_expired = alidiscountcouponchannelcommonvoucher.end_fixed_time
                        gmt_active = alidiscountcouponchannelcommonvoucher.start_fixed_time
                    elif alidiscountcouponchannelcommonvoucher.usetime_type == 3:
                        gmt_expired = gmt_create + datetime.timedelta(
                            days=alidiscountcouponchannelcommonvoucher.invalid_day)
                        gmt_active = gmt_create
                    else:
                        gmt_active = (gmt_create + datetime.timedelta(days=1)).strftime("%Y-%m-%d 00:00:00")
                        gmt_expired = (gmt_create + datetime.timedelta(
                            days=alidiscountcouponchannelcommonvoucher.invalid_day)).strftime("%Y-%m-%d 23:59:59")
                    data = {
                        'alidiscountcoupon_id': activity.id,
                        'voucher_id': coupon_id,
                        'user_id': user_id,
                        'template_id': activity.template_id,
                        'gmt_active': gmt_active,
                        'gmt_expired': gmt_expired,
                        'total_amount': activity.amount,
                        'gmt_create': gmt_create,
                        'available_amount': activity.amount,
                        'name': activity.activity_name,
                        'out_biz_no': out_biz_no,
                        'customer_user_id': user.id,
                        'alidiscountcoupon_level_id': alidiscountcoupon_level.id,
                        'level_id': alidiscountcoupon_level.level_id,
                        'mobile': user.mobile,
                        'coupon_channel': activity.coupon_channel
                    }
                    voucherinfo, create = AliDiscountCouponInfo.objects.get_or_create(defaults=data, voucher_id=coupon_id)
                    while True:
                        alidiscountcoupon_level = AliDiscountCouponLevel.objects.get(id=alidiscountcoupon_level_id)
                        instance_origin_take_number = alidiscountcoupon_level.take_number
                        instance_origin_receive_number = alidiscountcoupon_level.receive_number
                        instance_origin_remain_number = alidiscountcoupon_level.remain_number
                        instance_origin_p_take_number = alidiscountcoupon_level.p_take_number
                        instance_origin_p_receive_number = alidiscountcoupon_level.p_receive_number
                        instance_origin_p_remain_number = alidiscountcoupon_level.p_remain_number
                        instance_new_take_number = instance_origin_take_number + 1
                        instance_new_receive_number = instance_origin_receive_number + 1
                        instance_new_remain_number = instance_origin_remain_number - 1
                        instance_new_p_take_number = instance_origin_p_take_number + 1
                        instance_new_p_receive_number = instance_origin_p_receive_number + 1
                        instance_new_p_remain_number = instance_origin_p_remain_number - 1
                        result = AliDiscountCouponLevel.objects.filter(id=alidiscountcoupon_level_id, take_number=instance_origin_take_number).update(take_number=instance_new_take_number,
                            receive_number=instance_new_receive_number,
                            remain_number=instance_new_remain_number,
                            p_take_number=instance_new_p_take_number,
                            p_receive_number=instance_new_p_receive_number,
                            p_remain_number=instance_new_p_remain_number
                        )
                        if result == 0:
                            continue
                        break
                    try:
                        relation_set = alidiscountcoupon_level.child_set.all()
                        for relation in relation_set:
                            parent = relation.parent
                            parent.p_take_number += 1
                            parent.p_receive_number += 1
                            parent.p_remain_number -= 1
                            parent.save()
                    except:
                        pass
                    return Response({'success': '领取成功', 'coupon_id': voucherinfo.id}, status=status.HTTP_200_OK)
                else:
                    voucher_id = f'{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}{random_str(14)}'
                    user_id = user.ali_user_id
                    gmt_create = datetime.datetime.now()
                    alidiscountcouponchannelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
                    if alidiscountcouponchannelcommonvoucher.usetime_type == 2:
                        gmt_expired = alidiscountcouponchannelcommonvoucher.end_fixed_time
                        gmt_active = alidiscountcouponchannelcommonvoucher.start_fixed_time
                    elif alidiscountcouponchannelcommonvoucher.usetime_type == 3:
                        gmt_expired = gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)
                        gmt_active = gmt_create
                    else:
                        gmt_active = (gmt_create + datetime.timedelta(days=1)).strftime("%Y-%m-%d 00:00:00")
                        gmt_expired =(gmt_create+ datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)).strftime("%Y-%m-%d 23:59:59")
                    data = {
                        'alidiscountcoupon_id': activity.id,
                        'voucher_id': voucher_id,
                        'user_id': user_id,
                        'template_id': activity.template_id,
                        'gmt_active': gmt_active,
                        'gmt_expired': gmt_expired,
                        'total_amount': activity.amount,
                        'gmt_create': gmt_create,
                        'available_amount': activity.amount,
                        'name': activity.activity_name,
                        'out_biz_no': out_biz_no,
                        'customer_user_id': user.id,
                        'alidiscountcoupon_level_id': alidiscountcoupon_level.id,
                        'level_id': alidiscountcoupon_level.level_id,
                        'mobile': user.mobile,
                        'gmt_distributed': datetime.datetime.now(),
                        'coupon_channel': activity.coupon_channel
                    }
                    while True:
                        alidiscountcoupon_level = AliDiscountCouponLevel.objects.get(id=alidiscountcoupon_level_id)
                        instance_origin_take_number = alidiscountcoupon_level.take_number
                        instance_origin_receive_number = alidiscountcoupon_level.receive_number
                        instance_origin_max_number = alidiscountcoupon_level.max_number
                        instance_origin_p_take_number = alidiscountcoupon_level.p_take_number
                        instance_origin_p_receive_number = alidiscountcoupon_level.p_receive_number
                        instance_origin_p_max_number = alidiscountcoupon_level.p_max_number
                        instance_new_take_number = instance_origin_take_number + 1
                        instance_new_receive_number = instance_origin_receive_number + 1
                        instance_new_max_number = instance_origin_max_number + 1
                        instance_new_p_take_number = instance_origin_p_take_number + 1
                        instance_new_p_receive_number = instance_origin_p_receive_number + 1
                        instance_new_p_max_number = instance_origin_p_max_number + 1
                        result = AliDiscountCouponLevel.objects.filter(id=alidiscountcoupon_level_id, take_number=instance_origin_take_number).update(
                            take_number=instance_new_take_number,
                            receive_number=instance_new_receive_number,
                            max_number=instance_new_max_number,
                            p_take_number=instance_new_p_take_number,
                            p_receive_number=instance_new_p_receive_number,
                            p_max_number=instance_new_p_max_number
                        )
                        if result == 0:
                            continue
                        break
                    while True:
                        activity = AliDiscountCoupon.objects.get(id=activity_id)
                        activity_origin_send_count = activity.send_count
                        activity_origin_remain_number = activity.remain_number
                        activity_new_send_count = activity_origin_send_count + 1
                        activity_new_remain_number = activity_origin_remain_number - 1
                        result = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
                            send_count=activity_new_send_count,
                            remain_number=activity_new_remain_number
                        )
                        if result == 0:
                            continue
                        break
                    try:
                        relation_set = alidiscountcoupon_level.child_set.all()
                        for relation in relation_set:
                            parent = relation.parent
                            parent.p_take_number += 1
                            parent.p_receive_number += 1
                            parent.p_max_number += 1
                            parent.save()
                    except:
                        pass
                    voucherinfo, create = AliDiscountCouponInfo.objects.get_or_create(defaults=data, voucher_id=voucher_id)
                    if create:
                        return Response({'success': '领取成功', 'coupon_id': voucherinfo.id}, status=status.HTTP_200_OK)
                    else:
                        return Response({'error': '已经领取过了'}, status=status.HTTP_400_BAD_REQUEST)
        else:
            try:
                activity = AliDiscountCoupon.objects.get(id=identify)
            except:
                return Response({'error': '无效活动id,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
            user = self.request.iser
            alidiscountcoupon_level = AliDiscountCouponLevel.objects.filter(activity_id=activity.id).first()
            out_biz_no = f'100004{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
            try:
                channelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
                if channelcommonvoucher.distributed_limit_by_time == 1:
                    week = str(datetime.datetime.now().weekday())
                    enable_time = datetime.datetime.now().strftime('1970-01-01 %H:%M:%S')
                    alidiscountcoupondstributedlimit = AliDiscountCouponDistributedLimit.objects.filter(
                        ali_discount_coupon_common_voucher_id=channelcommonvoucher.id, weeks__contains=week,
                        start_enable_time__lte=enable_time, end_enable_time__gte=enable_time)
                    if not alidiscountcoupondstributedlimit:
                        return Response({'error': '没到活动派发时间'}, status=status.HTTP_400_BAD_REQUEST)
            except:
                pass
            if activity.is_white:
                is_white = AliDiscountCouponWhiteTable.objects.filter(mobile=user.mobile, alidiscountcoupon_id=activity.id)
                if not is_white:
                    return Response({'error': '您没有该优惠券领取权限，请联系客户经理参与活动。'}, status=status.HTTP_400_BAD_REQUEST)
            if activity.is_check_identity == 1:
                check_manager = User.objects.filter(mobile=user.mobile, is_active=1)
                if check_manager:
                    return Response({'error': '该活动暂不允许内部员工参与，如有疑问请咨询客服。'}, status=status.HTTP_400_BAD_REQUEST)
            if activity.max_number_by_day:
                begin_time = datetime.datetime.now().strftime('%Y-%m-%d 00:00:00')
                end_time = datetime.datetime.now().strftime('%Y-%m-%d 23:59:59')
                max_no = AliDiscountCouponInfo.objects.filter(alidiscountcoupon_id=activity.id,
                                                              gmt_create__gte=begin_time,
                                                              gmt_create__lte=end_time).count()
                if max_no >= activity.max_number_by_day:
                    return Response({'error': '今天的优惠券已领取完毕，请明天0点继续参与，感谢您对本活动的支持！'}, status=status.HTTP_400_BAD_REQUEST)
            if activity.max_number_by_user:
                max_no = AliDiscountCouponInfo.objects.filter(alidiscountcoupon_id=activity.id,
                                                              customer_user_id=user.id).count()
                if max_no >= activity.max_number_by_user:
                    return Response({'error': '用户参与活动次数已达上限，感谢您对本活动的支持！'}, status=status.HTTP_400_BAD_REQUEST)
            if alidiscountcoupon_level.remain_number <= 0:
                return Response({'error': '活动已达到派发上限'}, status=status.HTTP_400_BAD_REQUEST)
            query = AliDiscountCouponInfo.objects.filter(customer_user_id=user.id, alidiscountcoupon_id=activity.id)
            if 1 in query.values_list('status', flat=True):
                return Response({'error': '活动设定领1张使用1张规则'}, status=status.HTTP_400_BAD_REQUEST)
            elif activity.max_number_by_user <= query.count():
                return Response({'error': '活动已达到领取上限'}, status=status.HTTP_400_BAD_REQUEST)
            alidiscountcoupon_level_id = alidiscountcoupon_level.id
            activity_id = activity.id
            if activity.coupon_channel == 1:
                if not user.ali_user_id:
                    return Response({'error': '用户尚未关联支付宝,请使用支付宝【赋有】小程序授权登录'}, status=status.HTTP_400_BAD_REQUEST)
                alipay_obj = AlipayOpen()
                user_id = user.ali_user_id
                template_id = activity.template_id
                result = json.loads(alipay_obj.vouchersend(user_id, template_id, out_biz_no))
                if result['code'] != '10000':
                    logger.error(str(result))
                    try:
                        return Response({'error': result['sub_msg']}, status=status.HTTP_400_BAD_REQUEST)
                    except:
                        return Response({'error': '领取失败,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
                voucher_id = result['voucher_id']
                if activity.platform_id == 1:
                    result = json.loads(alipay_obj.voucherquery(voucher_id))
                    data = {
                        'alidiscountcoupon_id': activity.id,
                        'voucher_id': voucher_id,
                        'user_id': user_id,
                        'template_id': result['template_id'],
                        'gmt_active': result['gmt_active'],
                        'gmt_expired': result['gmt_expired'],
                        'total_amount': result['total_amount'],
                        'gmt_create': result['gmt_create'],
                        'available_amount': result['available_amount'],
                        'name': result['name'],
                        'out_biz_no': out_biz_no,
                        'customer_user_id': user.id,
                        'gmt_distributed': datetime.datetime.now(),
                        'alidiscountcoupon_level_id': alidiscountcoupon_level.id,
                        'level_id': alidiscountcoupon_level.level_id,
                        'mobile': user.mobile,
                        'coupon_channel': activity.coupon_channel
                    }
                else:
                    gmt_create = datetime.datetime.now()
                    alidiscountcouponchannelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
                    if alidiscountcouponchannelcommonvoucher.usetime_type == 2:
                        gmt_expired = alidiscountcouponchannelcommonvoucher.end_fixed_time
                        gmt_active = alidiscountcouponchannelcommonvoucher.start_fixed_time
                    elif alidiscountcouponchannelcommonvoucher.usetime_type == 3:
                        gmt_expired = gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)
                        gmt_active = gmt_create
                    else:
                        gmt_active = (gmt_create + datetime.timedelta(days=1)).strftime("%Y-%m-%d 00:00:00")
                        gmt_expired = (gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)).strftime("%Y-%m-%d 23:59:59")
                    data = {
                        'alidiscountcoupon_id': activity.id,
                        'voucher_id': voucher_id,
                        'user_id': user_id,
                        'template_id': activity.template_id,
                        'gmt_active': gmt_active,
                        'gmt_expired': gmt_expired,
                        'total_amount': activity.amount,
                        'gmt_create': gmt_create,
                        'available_amount': activity.amount,
                        'name': activity.activity_name,
                        'out_biz_no': out_biz_no,
                        'customer_user_id': user.id,
                        'gmt_distributed': gmt_create,
                        'alidiscountcoupon_level_id': alidiscountcoupon_level.id,
                        'level_id': alidiscountcoupon_level.level_id,
                        'mobile': user.mobile,
                        'coupon_channel': activity.coupon_channel
                    }
                voucherinfo, create = AliDiscountCouponInfo.objects.get_or_create(defaults=data, voucher_id=voucher_id)
                while True:
                    alidiscountcoupon_level = AliDiscountCouponLevel.objects.get(id=alidiscountcoupon_level_id)
                    instance_origin_take_number = alidiscountcoupon_level.take_number
                    instance_origin_receive_number = alidiscountcoupon_level.receive_number
                    instance_origin_remain_number = alidiscountcoupon_level.remain_number
                    instance_origin_p_take_number = alidiscountcoupon_level.p_take_number
                    instance_origin_p_receive_number = alidiscountcoupon_level.p_receive_number
                    instance_origin_p_remain_number = alidiscountcoupon_level.p_remain_number
                    instance_new_take_number = instance_origin_take_number + 1
                    instance_new_receive_number = instance_origin_receive_number + 1
                    instance_new_remain_number = instance_origin_remain_number - 1
                    instance_new_p_take_number = instance_origin_p_take_number + 1
                    instance_new_p_receive_number = instance_origin_p_receive_number + 1
                    instance_new_p_remain_number = instance_origin_p_remain_number - 1
                    result = AliDiscountCouponLevel.objects.filter(id=alidiscountcoupon_level_id, take_number=instance_origin_take_number).update(
                        take_number=instance_new_take_number,
                        receive_number=instance_new_receive_number,
                        remain_number=instance_new_remain_number,
                        p_take_number=instance_new_p_take_number,
                        p_receive_number=instance_new_p_receive_number,
                        p_remain_number=instance_new_p_remain_number
                    )
                    if result == 0:
                        continue
                    break
                while True:
                    activity = AliDiscountCoupon.objects.get(id=activity_id)
                    activity_origin_send_count = activity.send_count
                    activity_origin_remain_number = activity.remain_number
                    activity_new_send_count = activity_origin_send_count + 1
                    activity_new_remain_number = activity_origin_remain_number - 1
                    result = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
                        send_count=activity_new_send_count,
                        remain_number=activity_new_remain_number
                    )
                    if result == 0:
                        continue
                    break
                try:
                    relation_set = alidiscountcoupon_level.child_set.all()
                    for relation in relation_set:
                        parent = relation.parent
                        parent.p_take_number += 1
                        parent.p_receive_number += 1
                        parent.p_remain_number -= 1
                        parent.save()
                except:
                    pass
                if create:
                    return Response({'success': '领取成功', 'coupon_id': voucherinfo.id}, status=status.HTTP_200_OK)
                else:
                    return Response({'error': '已经领取过了'}, status=status.HTTP_400_BAD_REQUEST)
            elif activity.coupon_channel == 2:
                if user.new_openid:
                    appid = settings.CUSTOMER_APP_ID_NEW
                    openid = user.new_openid
                elif user.openid:
                    appid = settings.CUSTOMER_APP_ID
                    openid = user.openid
                else:
                    return Response({'error': '用户尚未关联微信,请使用微信【赋有】小程序授权登录'}, status=status.HTTP_400_BAD_REQUEST)
                if activity.platform_id == 13:
                    distribute_channel = Channel.objects.get(id=13)
                else:
                    distribute_channel = Channel.objects.get(id=9)
                data_json = {
                    "stock_id": activity.template_id,
                    "out_request_no": out_biz_no,
                    "appid": appid,
                    "stock_creator_mchid": activity.platform.mchid
                }
                data_dict = favor_distributed_coupons_sichun(data_json, openid, distribute_channel)
                if 'code' in data_dict:
                    return Response({'error': data_dict['message']}, status=status.HTTP_400_BAD_REQUEST)
                coupon_id = data_dict['coupon_id']
                voucherinfo = AliDiscountCouponInfo.objects.filter(voucher_id=coupon_id).first()
                if voucherinfo:
                    return Response({'error': '已经领取过了'}, status=status.HTTP_400_BAD_REQUEST)
                result = favor_query_coupons_sichun(coupon_id, openid, appid, distribute_channel)
                data = {
                    'alidiscountcoupon_id': activity.id,
                    'voucher_id': coupon_id,
                    'user_id': openid,
                    'template_id': result['stock_id'],
                    'gmt_active': result['available_begin_time'].replace('T', ' ').replace('+08:00', ''),
                    'gmt_expired': result['available_end_time'].replace('T', ' ').replace('+08:00', ''),
                    'total_amount': result['normal_coupon_information']['coupon_amount'] / 100,
                    'gmt_create': datetime.datetime.now(),
                    'available_amount': result['normal_coupon_information']['coupon_amount'] / 100,
                    'name': result['coupon_name'],
                    'out_biz_no': out_biz_no,
                    'customer_user_id': user.id,
                    'gmt_distributed': datetime.datetime.now(),
                    'alidiscountcoupon_level_id': alidiscountcoupon_level.id,
                    'level_id': alidiscountcoupon_level.level_id,
                    'mobile': user.mobile,
                    'coupon_channel': activity.coupon_channel
                }
                while True:
                    alidiscountcoupon_level = AliDiscountCouponLevel.objects.get(id=alidiscountcoupon_level_id)
                    instance_origin_take_number = alidiscountcoupon_level.take_number
                    instance_origin_receive_number = alidiscountcoupon_level.receive_number
                    instance_origin_remain_number = alidiscountcoupon_level.remain_number
                    instance_origin_p_take_number = alidiscountcoupon_level.p_take_number
                    instance_origin_p_receive_number = alidiscountcoupon_level.p_receive_number
                    instance_origin_p_remain_number = alidiscountcoupon_level.p_remain_number
                    instance_new_take_number = instance_origin_take_number + 1
                    instance_new_receive_number = instance_origin_receive_number + 1
                    instance_new_remain_number = instance_origin_remain_number - 1
                    instance_new_p_take_number = instance_origin_p_take_number + 1
                    instance_new_p_receive_number = instance_origin_p_receive_number + 1
                    instance_new_p_remain_number = instance_origin_p_remain_number - 1
                    result = AliDiscountCouponLevel.objects.filter(id=alidiscountcoupon_level_id, take_number=instance_origin_take_number).update(
                        take_number=instance_new_take_number,
                        receive_number=instance_new_receive_number,
                        remain_number=instance_new_remain_number,
                        p_take_number=instance_new_p_take_number,
                        p_receive_number=instance_new_p_receive_number,
                        p_remain_number=instance_new_p_remain_number
                    )
                    if result == 0:
                        continue
                    break
                while True:
                    activity = AliDiscountCoupon.objects.get(id=activity_id)
                    activity_origin_send_count = activity.send_count
                    activity_origin_remain_number = activity.remain_number
                    activity_new_send_count = activity_origin_send_count + 1
                    activity_new_remain_number = activity_origin_remain_number - 1
                    result = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
                        send_count=activity_new_send_count,
                        remain_number=activity_new_remain_number
                    )
                    if result == 0:
                        continue
                    break
                try:
                    relation_set = alidiscountcoupon_level.child_set.all()
                    for relation in relation_set:
                        parent = relation.parent
                        parent.p_take_number += 1
                        parent.p_receive_number += 1
                        parent.p_remain_number -= 1
                        parent.save()
                except:
                    pass
                voucherinfo, create = AliDiscountCouponInfo.objects.get_or_create(defaults=data, voucher_id=coupon_id)
                if create:
                    return Response({'success': '领取成功', 'coupon_id': voucherinfo.id}, status=status.HTTP_200_OK)
                else:
                    return Response({'error': '已经领取过了'}, status=status.HTTP_400_BAD_REQUEST)
            else:
                voucher_id = f'{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}{random_str(14)}'
                user_id = user.ali_user_id
                gmt_create = datetime.datetime.now()
                alidiscountcouponchannelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
                if alidiscountcouponchannelcommonvoucher.usetime_type == 2:
                    gmt_expired = alidiscountcouponchannelcommonvoucher.end_fixed_time
                    gmt_active = alidiscountcouponchannelcommonvoucher.start_fixed_time
                elif alidiscountcouponchannelcommonvoucher.usetime_type == 3:
                    gmt_expired = gmt_create + datetime.timedelta(
                        days=alidiscountcouponchannelcommonvoucher.invalid_day)
                    gmt_active = gmt_create
                else:
                    gmt_active = (gmt_create + datetime.timedelta(days=1)).strftime("%Y-%m-%d 00:00:00")
                    gmt_expired = (gmt_create + datetime.timedelta(
                        days=alidiscountcouponchannelcommonvoucher.invalid_day)).strftime("%Y-%m-%d 23:59:59")
                data = {
                    'alidiscountcoupon_id': activity.id,
                    'voucher_id': voucher_id,
                    'user_id': user_id,
                    'template_id': activity.template_id,
                    'gmt_active': gmt_active,
                    'gmt_expired': gmt_expired,
                    'total_amount': activity.amount,
                    'gmt_create': gmt_create,
                    'available_amount': activity.amount,
                    'name': activity.activity_name,
                    'out_biz_no': out_biz_no,
                    'customer_user_id': user.id,
                    'alidiscountcoupon_level_id': alidiscountcoupon_level.id,
                    'level_id': alidiscountcoupon_level.level_id,
                    'mobile': user.mobile,
                    'gmt_distributed': datetime.datetime.now(),
                    'coupon_channel': activity.coupon_channel
                }
                while True:
                    alidiscountcoupon_level = AliDiscountCouponLevel.objects.get(id=alidiscountcoupon_level_id)
                    instance_origin_take_number = alidiscountcoupon_level.take_number
                    instance_origin_receive_number = alidiscountcoupon_level.receive_number
                    instance_origin_remain_number = alidiscountcoupon_level.remain_number
                    instance_origin_p_take_number = alidiscountcoupon_level.p_take_number
                    instance_origin_p_receive_number = alidiscountcoupon_level.p_receive_number
                    instance_origin_p_remain_number = alidiscountcoupon_level.p_remain_number
                    instance_new_take_number = instance_origin_take_number + 1
                    instance_new_receive_number = instance_origin_receive_number + 1
                    instance_new_remain_number = instance_origin_remain_number - 1
                    instance_new_p_take_number = instance_origin_p_take_number + 1
                    instance_new_p_receive_number = instance_origin_p_receive_number + 1
                    instance_new_p_remain_number = instance_origin_p_remain_number - 1
                    result = AliDiscountCouponLevel.objects.filter(id=alidiscountcoupon_level_id, take_number=instance_origin_take_number).update(
                        take_number=instance_new_take_number,
                        receive_number=instance_new_receive_number,
                        remain_number=instance_new_remain_number,
                        p_take_number=instance_new_p_take_number,
                        p_receive_number=instance_new_p_receive_number,
                        p_remain_number=instance_new_p_remain_number
                    )
                    if result == 0:
                        continue
                    break
                while True:
                    activity = AliDiscountCoupon.objects.get(id=activity_id)
                    activity_origin_send_count = activity.send_count
                    activity_origin_remain_number = activity.remain_number
                    activity_new_send_count = activity_origin_send_count + 1
                    activity_new_remain_number = activity_origin_remain_number - 1
                    result = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
                        send_count=activity_new_send_count,
                        remain_number=activity_new_remain_number
                    )
                    if result == 0:
                        continue
                    break
                try:
                    relation_set = alidiscountcoupon_level.child_set.all()
                    for relation in relation_set:
                        parent = relation.parent
                        parent.p_take_number += 1
                        parent.p_receive_number += 1
                        parent.p_remain_number -= 1
                        parent.save()
                except:
                    pass
                voucherinfo, create = AliDiscountCouponInfo.objects.get_or_create(defaults=data, voucher_id=voucher_id)
                if create:
                    return Response({'success': '领取成功', 'coupon_id': voucherinfo.id}, status=status.HTTP_200_OK)
                else:
                    return Response({'error': '已经领取过了'}, status=status.HTTP_400_BAD_REQUEST)

    def partial_update(self, request, *args, **kwargs):
        instance = self.get_object()
        user = self.request.iser
        if instance.status != 0:
            return Response({'error': '当前券状态不可领取'}, status=status.HTTP_400_BAD_REQUEST)
        # if user.is_auth != 2:
        #     return Response({'error': '请先完成实名认证'}, status=status.HTTP_400_BAD_REQUEST)
        activity = instance.alidiscountcoupon
        if user.is_auth != 2 and activity.is_need_auth == 1:
            return Response({'error': '请先完成实名认证'}, status=status.HTTP_400_BAD_REQUEST)
        if activity.coupon_channel == 1:
            if not user.ali_user_id:
                return Response({'error': '用户尚未关联支付宝,请使用支付宝【赋有】小程序授权登录'}, status=status.HTTP_400_BAD_REQUEST)
            alipay_obj = AlipayOpen()
            user_id = user.ali_user_id
            template_id = activity.template_id
            out_biz_no = instance.out_biz_no
            result = json.loads(alipay_obj.vouchersend(user_id, template_id, out_biz_no))
            if result['code'] != '10000':
                logger.error(str(result))
                try:
                    return Response({'error': result['sub_msg']}, status=status.HTTP_400_BAD_REQUEST)
                except:
                    return Response({'error': '领取失败,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
            voucher_id = result['voucher_id']
            voucherinfo = AliDiscountCouponInfo.objects.filter(voucher_id=voucher_id).first()
            if voucherinfo:
                return Response({'error': '已经领取过了'}, status=status.HTTP_400_BAD_REQUEST)
            if activity.platform_id == 1:
                result = json.loads(alipay_obj.voucherquery(voucher_id))
                instance.voucher_id = voucher_id
                instance.user_id = user_id
                instance.template_id = result['template_id']
                instance.gmt_active = result['gmt_active']
                instance.gmt_expired = result['gmt_expired']
                instance.total_amount = result['total_amount']
                instance.gmt_create = result['gmt_create']
                instance.available_amount = result['available_amount']
                instance.name = result['name']
                instance.status = 1
                instance.save()
            else:
                gmt_create = datetime.datetime.now()
                alidiscountcouponchannelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
                if alidiscountcouponchannelcommonvoucher.usetime_type == 2:
                    gmt_expired = alidiscountcouponchannelcommonvoucher.end_fixed_time
                    gmt_active = alidiscountcouponchannelcommonvoucher.start_fixed_time
                elif alidiscountcouponchannelcommonvoucher.usetime_type == 3:
                    gmt_expired = gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)
                    gmt_active = gmt_create
                else:
                    gmt_active = (gmt_create + datetime.timedelta(days=1)).strftime("%Y-%m-%d 00:00:00")
                    gmt_expired = (gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)).strftime("%Y-%m-%d 23:59:59")
                instance.voucher_id = voucher_id
                instance.user_id = user_id
                instance.template_id = activity.template_id
                instance.gmt_active = gmt_active
                instance.gmt_expired = gmt_expired
                instance.total_amount = activity.amount
                instance.gmt_create = gmt_create
                instance.available_amount = activity.amount
                instance.name = activity.activity_name
                instance.status = 1
                instance.save()
            try:
                alidiscountcoupon_level = instance.alidiscountcoupon_level
                alidiscountcoupon_level.receive_number += 1
                alidiscountcoupon_level.p_receive_number += 1
                alidiscountcoupon_level.save()
                relation_set = alidiscountcoupon_level.child_set.all()
                for relation in relation_set:
                    parent = relation.parent
                    parent.p_receive_number += 1
                    parent.save()
            except:
                pass
            if not user.level_id:
                user.level_id = instance.level_id
                user.user_id = instance.companyuser_id
                user.save()
            return Response({'success': '领取成功', 'coupon_id': instance.id}, status=status.HTTP_200_OK)
        elif activity.coupon_channel == 2:
            if user.new_openid:
                appid = settings.CUSTOMER_APP_ID_NEW
                openid = user.new_openid
            elif user.openid:
                appid = settings.CUSTOMER_APP_ID
                openid = user.openid
            else:
                return Response({'error': '用户尚未关联微信,请使用微信【赋有】小程序授权登录'}, status=status.HTTP_400_BAD_REQUEST)
            if activity.platform_id == 13:
                distribute_channel = Channel.objects.get(id=13)
            else:
                distribute_channel = Channel.objects.get(id=9)
            data_json = {
                "stock_id": activity.template_id,
                "out_request_no": instance.out_biz_no,
                "appid": appid,
                "stock_creator_mchid": activity.platform.mchid
            }
            data_dict = favor_distributed_coupons_sichun(data_json, openid, distribute_channel)
            if 'code' in data_dict:
                return Response({'error': data_dict['message']}, status=status.HTTP_400_BAD_REQUEST)
            coupon_id = data_dict['coupon_id']
            voucherinfo = AliDiscountCouponInfo.objects.filter(voucher_id=coupon_id).first()
            if voucherinfo:
                return Response({'error': '已经领取过了'}, status=status.HTTP_400_BAD_REQUEST)
            result = favor_query_coupons_sichun(coupon_id, openid, appid, distribute_channel)
            instance.voucher_id = coupon_id
            instance.user_id = openid
            instance.template_id = result['stock_id']
            instance.gmt_active = result['available_begin_time'].replace('T', ' ').replace('+08:00', '')
            instance.gmt_expired = result['available_end_time'].replace('T', ' ').replace('+08:00', '')
            instance.total_amount = result['normal_coupon_information']['coupon_amount']/100
            instance.gmt_create = datetime.datetime.now()
            instance.available_amount = result['normal_coupon_information']['coupon_amount']/100
            instance.name = result['coupon_name']
            instance.status = 1
            instance.save()
            try:
                alidiscountcoupon_level = instance.alidiscountcoupon_level
                alidiscountcoupon_level.receive_number += 1
                alidiscountcoupon_level.p_receive_number += 1
                alidiscountcoupon_level.save()
                relation_set = alidiscountcoupon_level.child_set.all()
                for relation in relation_set:
                    parent = relation.parent
                    parent.p_receive_number += 1
                    parent.save()
            except:
                pass
            if not user.level_id:
                user.level_id = instance.level_id
                user.user_id = instance.companyuser_id
                user.save()
            return Response({'success': '领取成功', 'coupon_id': instance.id}, status=status.HTTP_200_OK)
        elif activity.coupon_channel == 5:
            meituan_result = favor_meituan_coupons(instance.out_biz_no, activity.template_id, user.mobile)
            if meituan_result['status'] != 'success':
                return Response({'error': meituan_result['errorMsg']}, status=status.HTTP_400_BAD_REQUEST)
            coupon_id = meituan_result['data'][0]['code']
            voucherinfo = AliDiscountCouponInfo.objects.filter(voucher_id=coupon_id).first()
            if voucherinfo:
                return Response({'error': '已经领取过了'}, status=status.HTTP_400_BAD_REQUEST)
            user_id = user.mobile
            gmt_create = datetime.datetime.now()
            alidiscountcouponchannelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
            if alidiscountcouponchannelcommonvoucher.usetime_type == 2:
                gmt_expired = alidiscountcouponchannelcommonvoucher.end_fixed_time
                gmt_active = alidiscountcouponchannelcommonvoucher.start_fixed_time
            elif alidiscountcouponchannelcommonvoucher.usetime_type == 3:
                gmt_expired = gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)
                gmt_active = gmt_create
            else:
                gmt_active = (gmt_create + datetime.timedelta(days=1)).strftime("%Y-%m-%d 00:00:00")
                gmt_expired = (gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)).strftime("%Y-%m-%d 23:59:59")
            instance.voucher_id = coupon_id
            instance.user_id = user_id
            instance.template_id = activity.template_id
            instance.gmt_active = gmt_active
            instance.gmt_expired = gmt_expired
            instance.total_amount = activity.amount
            instance.gmt_create = datetime.datetime.now()
            instance.available_amount = activity.amount
            instance.name = activity.activity_name
            instance.status = 1
            instance.save()
            try:
                alidiscountcoupon_level = instance.alidiscountcoupon_level
                alidiscountcoupon_level.receive_number += 1
                alidiscountcoupon_level.p_receive_number += 1
                alidiscountcoupon_level.save()
                relation_set = alidiscountcoupon_level.child_set.all()
                for relation in relation_set:
                    parent = relation.parent
                    parent.p_receive_number += 1
                    parent.save()
            except:
                pass
            if not user.level_id:
                user.level_id = instance.level_id
                user.user_id = instance.companyuser_id
                user.save()
            return Response({'success': '领取成功', 'coupon_id': instance.id}, status=status.HTTP_200_OK)
        else:
            voucher_id = f'{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}{random_str(14)}'
            user_id = user.ali_user_id
            gmt_create = datetime.datetime.now()
            alidiscountcouponchannelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
            if alidiscountcouponchannelcommonvoucher.usetime_type == 2:
                gmt_expired = alidiscountcouponchannelcommonvoucher.end_fixed_time
                gmt_active = alidiscountcouponchannelcommonvoucher.start_fixed_time
            elif alidiscountcouponchannelcommonvoucher.usetime_type == 3:
                gmt_expired = gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)
                gmt_active = gmt_create
            else:
                gmt_active = (gmt_create + datetime.timedelta(days=1)).strftime("%Y-%m-%d 00:00:00")
                gmt_expired = (gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)).strftime("%Y-%m-%d 23:59:59")
            instance.voucher_id = voucher_id
            instance.user_id = user_id
            instance.gmt_active = gmt_active
            instance.gmt_expired = gmt_expired
            instance.total_amount = activity.amount
            instance.gmt_create = gmt_create
            instance.available_amount = activity.amount
            instance.name = activity.activity_name
            instance.status = 1
            instance.save()
            try:
                alidiscountcoupon_level = instance.alidiscountcoupon_level
                alidiscountcoupon_level.receive_number += 1
                alidiscountcoupon_level.p_receive_number += 1
                alidiscountcoupon_level.save()
                relation_set = alidiscountcoupon_level.child_set.all()
                for relation in relation_set:
                    parent = relation.parent
                    parent.p_receive_number += 1
                    parent.save()
            except:
                pass
            if not user.level_id:
                user.level_id = instance.level_id
                user.user_id = instance.companyuser_id
                user.save()
            return Response({'success': '领取成功', 'coupon_id': instance.id}, status=status.HTTP_200_OK)

    def coupon(self, request):
        identify = self.request.query_params.get('identify', None)
        try:
            qrcode = AliDiscountCouponQRCode.objects.get(identify=identify)
        except:
            qrcode = AliDiscountCouponQRCode.objects.get(identify='3fYeMxFNDy8UINSvWGoDH20jTxa9CVuu')
        activity = qrcode.alidiscountcoupon_level.activity
        data = {}
        data['activity_name'] = activity.activity_name
        data['amount'] = activity.amount
        data['floor_amount'] = activity.floor_amount
        data['publish_end_time'] = activity.publish_end_time.strftime('%Y年%m月%d日 %H:%M:%S')
        if activity.coupon_type == 2:
            channelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
            if channelcommonvoucher.usetime_type == 2:
                data['usetime_type'] = f'固定时间段{channelcommonvoucher.start_fixed_time.strftime("%Y.%m.%d %H:%M:%S")}-{channelcommonvoucher.end_fixed_time.strftime("%Y.%m.%d %H:%M:%S")}'
            elif channelcommonvoucher.usetime_type == 3:
                data['usetime_type'] = f'领取后立即生效有效时间{channelcommonvoucher.invalid_day}天'
            else:
                data['usetime_type'] = f'领取后次日凌晨生效有效时间{channelcommonvoucher.invalid_day}天'
        else:
            data['usetime_type'] = ''
        data['activity_description'] = activity.activity_description
        data['qrcode_state'] = qrcode.qrcode_state
        return render(request, 'wx_scan_error.html', {'data': data})

    def couponexplain(self, request):
        user = self.request.iser
        queryset = AliDiscountCouponInfo.objects.filter(customer_user_id=user.id, status=1, gmt_expired__gte=datetime.datetime.now(), alidiscountcoupon__coupon_channel=1).order_by('-id')
        data = AliDiscountCouponInfoListModelSerializer(queryset, many=True).data
        return Response(data, status=status.HTTP_200_OK)

    def merchantscoupon(self, request):
        user = self.request.iser
        goods_id_array = self.request.data.get('goods_id_array', None)
        if not goods_id_array:
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        if type([]) != type(goods_id_array):
            return Response({'error': '参数类型有误'}, status=status.HTTP_400_BAD_REQUEST)
        queryset = AliDiscountCouponInfo.objects.filter(customer_user_id=user.id, status=1, gmt_expired__gte=datetime.datetime.now(), gmt_active__lte=datetime.datetime.now(), alidiscountcoupon__coupon_channel=3, alidiscountcoupon__alidiscountcoupongoodsavailable__goods_id__in=goods_id_array).distinct().order_by('-id')
        AliDiscountCouponInfo.objects.filter(customer_user_id=user.id, status=1, gmt_expired__lte=datetime.datetime.now(), alidiscountcoupon__coupon_channel=3).update(status=12)
        data = AliDiscountCouponInfoListModelSerializer(queryset, many=True).data
        return Response(data, status=status.HTTP_200_OK)

    def generatescheme(self, request):
        redis_conn = get_redis_connection("scheme")
        access_token = redis_conn.get('access_token')
        if access_token is None:
            access_token = redis_scheme_token()
        else:
            access_token = access_token.decode()
        identify = self.request.query_params.get('identify', None)
        try:
            sendsms = SpeedSendSMS.objects.get(identify=identify)
        except:
            return render(request, 'h5_fill_fail.html', {'data': '无效活动链接'})
        if sendsms.is_send == 2:
            return render(request, 'h5_fill_fail.html', {'data': '活动链接已被占用'})
        body = {
                    "jump_wxa":
                        {
                            "path": "pages/fill_info_h5_skip/fill_info_h5_skip",
                            "query": identify,
                            "env_version": "develop"
                        },
                    "expire_type": 1,
                    "expire_interval":1
                }
        headers = {'Content-Type': 'application/json'}
        url = f'https://api.weixin.qq.com/wxa/generatescheme?access_token={access_token}'
        response = requests.post(url=url, data=json.dumps(body), headers=headers)
        result = response.json()
        if result['errcode'] == 0:
            openlink = result['openlink']
        else:
            openlink = ''
        return render(request, 'h5_fill_info.html', {'data': openlink})

    def allow_merchant(self, request):
        identify = self.request.query_params.get('identify', None)
        alidiscountcoupon_id = self.request.query_params.get('alidiscountcoupon_id', None)
        page = self.request.query_params.get('page', 1)
        pagesize = self.request.query_params.get('pagesize', 10)
        if identify:
            if len(identify) == 32:
                try:
                    qrcode = AliDiscountCouponQRCode.objects.get(identify=identify)
                except:
                    return Response({'error': '无效二维码,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
                activity = qrcode.alidiscountcoupon_level.activity
            elif len(identify) == 48:
                try:
                    alidiscountcouponmanagerqrcode = AliDiscountCouponManagerQRCode.objects.get(identify=identify)
                except:
                    return Response({'error': '无效二维码,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
                activity = alidiscountcouponmanagerqrcode.alidiscountcoupon
            elif len(identify) == 64:
                try:
                    alidiscountcoupon_level = AliDiscountCouponLevel.objects.get(identify=identify)
                except:
                    return Response({'error': '无效二维码,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
                activity = alidiscountcoupon_level.activity
            else:
                try:
                    activity = AliDiscountCoupon.objects.get(id=identify)
                except:
                    return Response({'error': '无效活动id,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
        elif alidiscountcoupon_id:
            try:
                activity = AliDiscountCoupon.objects.get(id=alidiscountcoupon_id)
            except:
                return Response({'error': '无效活动id,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
        else:
            return Response({'error': '无效活动id,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
        # queryset = Merchant.objects.filter(alidiscountcouponmerchant__alidiscountcoupon_id=activity.id).distinct()
        longitude = self.request.query_params.get('longitude', None)
        latitude = self.request.query_params.get('latitude', None)

        # if not all([longitude, latitude]):
        #     pass
        # else:
        #     gcd_formula = "6371 * acos(least(greatest(cos(radians(%s)) * cos(radians(latitude)) * cos(radians(longitude) - radians(%s)) + sin(radians(%s)) * sin(radians(latitude)) , -1), 1))"
        #     sql = RawSQL(gcd_formula, (latitude, longitude, latitude))
        #     queryset = queryset.annotate(distance=sql).order_by(F('distance').asc(nulls_last=True))
        # page = self.paginate_queryset(queryset)
        # if page is not None:
        #     serializer = MerchantListModelSerializer(page, many=True, context={'longitude': longitude, 'latitude': latitude})
        #     return self.get_paginated_response(serializer.data)
        # serializer = MerchantListModelSerializer(queryset, many=True, context={'longitude': longitude, 'latitude': latitude})
        # return Response(serializer.data)

        response_data = {}
        conn = pymysql.connect(host=settings.DATABASES['default']['HOST'],
                               port=settings.DATABASES['default']['PORT'],
                               database=settings.DATABASES['default']['NAME'],
                               user=settings.DATABASES['default']['USER'],
                               password=settings.DATABASES['default']['PASSWORD'])
        cursor = conn.cursor(cursor=pymysql.cursors.SSDictCursor)
        sql = f'SELECT COUNT(*) AS max_count FROM tb_ali_discount_coupon_merchant WHERE alidiscountcoupon_id={activity.id};'
        cursor.execute(sql)
        max_count = cursor.fetchone()['max_count']
        response_data['counts'] = max_count
        response_data['page'] = int(page)
        response_data['pagesize'] = int(pagesize)
        response_data['pages'] = math.ceil(max_count/int(pagesize))
        if not all([longitude, latitude]):
            sql = f'''SELECT id,name,store_address,longitude,latitude,store_header_copy,managermobile,store_logo_copy,short_name,open_work_time,close_work_time FROM tb_merchant WHERE id IN (SELECT merchant_id FROM tb_ali_discount_coupon_merchant WHERE alidiscountcoupon_id={alidiscountcoupon_id}) AND latitude IS NOT NULL LIMIT {(int(page)-1)*int(pagesize)},{int(pagesize)};'''
        else:
            sql = f'''SELECT id,name,store_address,longitude,latitude,store_header_copy,managermobile,store_logo_copy,short_name,open_work_time,close_work_time,(6371 * acos(cos(radians({latitude})) * cos(radians(latitude)) * cos( radians(longitude) - radians({longitude})) + sin(radians({latitude})) * sin(radians(latitude)))) AS distance FROM tb_merchant WHERE id IN (SELECT merchant_id FROM tb_ali_discount_coupon_merchant WHERE alidiscountcoupon_id={alidiscountcoupon_id}) AND latitude  IS NOT NULL ORDER BY distance LIMIT {(int(page)-1)*int(pagesize)},{int(pagesize)};'''
        try:
            cursor.execute(sql)
            rows = cursor.fetchall()
        finally:
            cursor.close()
            conn.close()
        for row in rows:
            distance = row['distance']
            if distance < 1:
                row['distance'] = f'{int(distance * 1000)} m'
            else:
                row['distance'] = f'{Decimal(str(distance)).quantize(Decimal("0.00"))} km'
            row['store_header_copy'] = f'https://circle.sutpay.cn/{row["store_header_copy"]}'
            row['store_logo_copy'] = f'https://circle.sutpay.cn/{row["store_logo_copy"]}'
        response_data['lists'] = rows
        return Response(response_data, status=status.HTTP_200_OK)

    def allow_merchant_map(self, request):
        # identify = self.request.query_params.get('identify', None)
        # longitude = self.request.query_params.get('longitude', None)
        # latitude = self.request.query_params.get('latitude', None)
        # search = self.request.query_params.get('search', None)
        # distance = self.request.query_params.get('distance', 500)
        # distance = int(distance) / 1000
        # user = self.request.iser
        # if not all([longitude, latitude]):
        #     return Response({'error': '须上传当前位置经纬度'}, status=status.HTTP_400_BAD_REQUEST)
        # if not all([identify]):
        #     return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        # if len(identify) == 32:
        #     try:
        #         qrcode = AliDiscountCouponQRCode.objects.get(identify=identify)
        #     except:
        #         return Response({'error': '无效二维码,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
        #     activity = qrcode.alidiscountcoupon_level.activity
        # elif len(identify) == 48:
        #     try:
        #         alidiscountcouponmanagerqrcode = AliDiscountCouponManagerQRCode.objects.get(identify=identify)
        #     except:
        #         return Response({'error': '无效二维码,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
        #     activity = alidiscountcouponmanagerqrcode.alidiscountcoupon
        # elif len(identify) == 64:
        #     try:
        #         alidiscountcoupon_level = AliDiscountCouponLevel.objects.get(identify=identify)
        #     except:
        #         return Response({'error': '无效二维码,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
        #     activity = alidiscountcoupon_level.activity
        # else:
        #     try:
        #         activity = AliDiscountCoupon.objects.get(id=identify)
        #     except:
        #         return Response({'error': '无效活动id,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
        # queryset = Merchant.objects.filter(is_online=2, alidiscountcouponmerchant__alidiscountcoupon_id=activity.id, latitude__isnull=False).distinct()
        # response_data = {}
        # response_data['max_count'] = len(queryset)
        # response_data['count'] = len(queryset)
        # response_data['activity_info'] = AliDiscountCouponMapModelSerializer(activity, context={'user': user}).data
        # response_data['longitude'] = longitude
        # response_data['latitude'] = latitude
        # if search:
        #     queryset = queryset.filter(Q(short_name__contains=search) | Q(name__contains=search))
        #     response_data['count'] = len(queryset)
        # gcd_formula = "6371 * acos(least(greatest(cos(radians(%s)) * cos(radians(latitude)) * cos(radians(longitude) - radians(%s)) + sin(radians(%s)) * sin(radians(latitude)) , -1), 1))"
        # sql = RawSQL(gcd_formula, (latitude, longitude, latitude))
        # queryset = queryset.annotate(distance=sql).order_by(F('distance').asc(nulls_last=True))
        # if queryset:
        #     first_quert = queryset.first()
        #     response_data['longitude'] = first_quert.longitude
        #     response_data['latitude'] = first_quert.latitude
        # # queryset = queryset.annotate(distance=sql).filter(distance__lt=distance).order_by(F('distance').asc(nulls_last=True))
        # serializer = MerchantListModelSerializer(queryset, many=True, context={'longitude': longitude, 'latitude': latitude})
        # response_data['merchant_list'] = serializer.data
        # return Response(response_data, status=status.HTTP_200_OK)

        longitude = self.request.query_params.get('longitude', '')
        latitude = self.request.query_params.get('latitude', '')
        distance = self.request.query_params.get('distance', 2000)
        search = self.request.query_params.get('search', None)
        alidiscountcoupon_id = self.request.query_params.get('alidiscountcoupon_id', None)
        try:
            distance = int(distance)
            distance = distance * 1.5
            if distance > 50000:
                distance = 50000
            distance = distance / 1000
        except:
            return Response({'error': '距离参数格式有误'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            alidiscountcoupon = AliDiscountCoupon.objects.get(id=alidiscountcoupon_id)
        except:
            return Response({"count": 0, "merchant_list": [], "max_count": 0, "longitude": longitude, "latitude": latitude}, status=status.HTTP_200_OK)
        if not all([latitude, longitude]):
            return Response({'error': '请上传定位经纬度'}, status=status.HTTP_400_BAD_REQUEST)
        conn = pymysql.connect(host=settings.DATABASES['default']['HOST'],
                               port=settings.DATABASES['default']['PORT'],
                               database=settings.DATABASES['default']['NAME'],
                               user=settings.DATABASES['default']['USER'],
                               password=settings.DATABASES['default']['PASSWORD'])
        cursor = conn.cursor(cursor=pymysql.cursors.SSDictCursor)
        sql = f'SELECT COUNT(*) AS max_count FROM tb_ali_discount_coupon_merchant WHERE alidiscountcoupon_id={alidiscountcoupon_id};'
        cursor.execute(sql)
        max_count = cursor.fetchone()['max_count']
        if search:
            condition = f' AND (name LIKE "%{search}%" OR wyfMerchantID LIKE "%{search}%" OR store_address LIKE "%{search}%")'
            sql = f'''SELECT id,name,store_address,longitude,latitude,store_header_copy,managermobile,store_logo_copy,short_name,open_work_time,close_work_time,(6371 * acos(cos(radians({latitude})) * cos(radians(latitude)) * cos( radians(longitude) - radians({longitude})) + sin(radians({latitude})) * sin(radians(latitude)))) AS distance FROM tb_merchant WHERE id IN (SELECT merchant_id FROM tb_ali_discount_coupon_merchant WHERE alidiscountcoupon_id={alidiscountcoupon_id}) AND latitude IS NOT NULL {condition};'''
        else:
            sql = f'''SELECT id,name,store_address,longitude,latitude,store_header_copy,managermobile,store_logo_copy,short_name,open_work_time,close_work_time,(6371 * acos(cos(radians({latitude})) * cos(radians(latitude)) * cos( radians(longitude) - radians({longitude})) + sin(radians({latitude})) * sin(radians(latitude)))) AS distance FROM tb_merchant WHERE id IN (SELECT merchant_id FROM tb_ali_discount_coupon_merchant WHERE alidiscountcoupon_id={alidiscountcoupon_id}) AND latitude IS NOT NULL HAVING distance<={distance};'''
        try:
            cursor.execute(sql)
            rows = cursor.fetchall()
        finally:
            cursor.close()
            conn.close()
        for row in rows:
            distance = row['distance']
            if distance < 1:
                row['distance'] = f'{int(distance * 1000)} m'
            else:
                row['distance'] = f'{Decimal(str(distance)).quantize(Decimal("0.00"))} km'
            row['store_header_copy'] = f'https://circle.sutpay.cn/{row["store_header_copy"]}'
            row['store_logo_copy'] = f'https://circle.sutpay.cn/{row["store_logo_copy"]}'
        if rows:
            longitude = rows[0]['longitude']
            latitude = rows[0]['latitude']
        response_data = {}
        response_data['max_count'] = max_count
        response_data['count'] = len(rows)
        response_data['merchant_list'] = rows
        response_data['longitude'] = longitude
        response_data['latitude'] = latitude
        return Response(response_data, status=status.HTTP_200_OK)

    def applet(self, request):
        HTTP_USER_AGENT = self.request.environ['HTTP_USER_AGENT']
        if 'WeChat' in HTTP_USER_AGENT or 'MicroMessenger' in HTTP_USER_AGENT:
            return render(request, 'wx_open_error.html')
        else:
            identify = self.request.query_params.get('identify', '')
            return render(request, 'jump_applet.html', {'data': identify})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        if instance.status in [1, 8, 9]:
            alidiscountcoupon = instance.alidiscountcoupon
            if alidiscountcoupon.coupon_channel == 1:
                alipayopen = AlipayOpen()
                result = json.loads(alipayopen.voucherquery(instance.voucher_id))
                if result['status'] == 'USED':
                    alidiscountcoupon.use_count += 1
                    alidiscountcoupon.save()
                    try:
                        if 'bill_details' in result:
                            for bill_datail in result['bill_details']:
                                instance.gmt_use = bill_datail['gmt_create']
                                bill_datail['voucherinfo_id'] = instance.id
                                AliDiscountCouponBillDetails.objects.create(**bill_datail)
                    except:
                        pass
                    try:
                        alidiscountcoupon_level = instance.alidiscountcoupon_level
                        alidiscountcoupon_level.use_number += 1
                        alidiscountcoupon_level.p_use_number += 1
                        alidiscountcoupon_level.save()
                        relation_set = alidiscountcoupon_level.child_set.all()
                        for relation in relation_set:
                            parent = relation.parent
                            parent.p_use_number += 1
                            parent.save()
                    except:
                        pass
                instance.status = instance.STATUS_ENUM[result['status']]
                instance.save()
            elif alidiscountcoupon.coupon_channel == 2:
                coupon_id = instance.voucher_id
                openid = instance.user_id
                appid = instance.appid
                if alidiscountcoupon.platform_id == 13:
                    distribute_channel = Channel.objects.get(id=13)
                else:
                    distribute_channel = Channel.objects.get(id=9)
                result = favor_query_coupons_sichun(coupon_id, openid, appid, distribute_channel)
                try:
                    if result['status'] == 'USED':
                        alidiscountcoupon.use_count += 1
                        alidiscountcoupon.save()
                        try:
                            if 'bill_details' in result:
                                for bill_datail in result['bill_details']:
                                    instance.gmt_use = bill_datail['gmt_create']
                                    bill_datail['voucherinfo_id'] = instance.id
                                    AliDiscountCouponBillDetails.objects.create(**bill_datail)
                        except:
                            pass
                        try:
                            alidiscountcoupon_level = instance.alidiscountcoupon_level
                            alidiscountcoupon_level.use_number += 1
                            alidiscountcoupon_level.p_use_number += 1
                            alidiscountcoupon_level.save()
                            relation_set = alidiscountcoupon_level.child_set.all()
                            for relation in relation_set:
                                parent = relation.parent
                                parent.p_use_number += 1
                                parent.save()
                        except:
                            pass
                        instance.status = 7
                        instance.gmt_use = datetime.datetime.now()
                    elif result['status'] == 'EXPIRED':
                        instance.status = 12
                    instance.save()
                except:
                    pass
        serializer = self.get_serializer(instance)
        return Response(serializer.data)


class GoodsModelViewSet(ModelViewSet):
    '''商品'''

    pagination_class = MyPage
    filter_backends = (filters.SearchFilter, DjangoFilterBackend)
    filter_class = GoodsFilter
    search_fields = ('name',)

    def get_queryset(self):
        sale_sort = self.request.query_params.get('sale_sort', '')
        price_sort = self.request.query_params.get('price_sort', '')
        soldout = self.request.query_params.get('soldout', '')
        level_id = self.request.query_params.get('level_id', '')
        alidiscountcoupon_id = self.request.query_params.get('alidiscountcoupon_id', '')
        # if alidiscountcoupon_id:
        queryset = Goods.objects.filter(id=1)
        return queryset
        if self.action == 'list':
            if soldout == '1':
                if level_id:
                    queryset = Goods.objects.filter(is_launched=1, launchedgoods__stock__gt=0, launchedgoods__is_launched=1, launchedgoods__level_id=level_id).distinct().order_by('-launchedgoods__stock')
                else:
                    queryset = Goods.objects.filter(is_launched=1, stock__gt=0).order_by('-stock')
            elif soldout == '2':
                if level_id:
                    queryset = Goods.objects.filter(is_launched=1, launchedgoods__stock=0, launchedgoods__is_launched=1, launchedgoods__level_id=level_id).distinct().order_by('-launchedgoods__stock')
                else:
                    queryset = Goods.objects.filter(is_launched=1, stock=0).order_by('-stock')
            else:
                if level_id:
                    queryset = Goods.objects.filter(is_launched=1, launchedgoods__is_launched=1, launchedgoods__level_id=level_id).distinct().order_by('-launchedgoods__stock')
                else:
                    queryset = Goods.objects.filter(is_launched=1).order_by('-stock')
        else:
            if level_id:
                queryset = Goods.objects.filter(is_launched=1).order_by('-launchedgoods__stock')
            else:
                queryset = Goods.objects.filter(is_launched=1).order_by('-stock')
        if sale_sort == '1':
            queryset = queryset.order_by('sales')
        elif sale_sort == '2':
            queryset = queryset.order_by('-sales')
        elif price_sort == '1':
            queryset = queryset.order_by('price')
        elif price_sort == '2':
            queryset = queryset.order_by('-price')
        return queryset

    def get_serializer_class(self):
        if self.action == 'list':
            return GoodsListModelSerializer
        else:
            return GoodsRetrieveModelSerializer

    def get_serializer_context(self):
        level_id = self.request.query_params.get('level_id', None)
        return {'level_id': level_id}


class LaunchedGoodsModelViewSet(ModelViewSet):
    '''上架商品'''

    pagination_class = MyPage
    filter_backends = (filters.SearchFilter, DjangoFilterBackend)
    filter_class = LaunchedGoodsFilter
    search_fields = ('name',)

    def get_queryset(self):
        sort = self.request.query_params.get('sort', '')
        level_id = self.request.query_params.get('level_id', None)
        alidiscountcoupon_id = self.request.query_params.get('alidiscountcoupon_id', None)
        queryset = LaunchedGoods.objects.filter(id=1)
        return queryset
        if not level_id and not alidiscountcoupon_id:
            if self.action == 'list':
                queryset = LaunchedGoods.objects.filter(is_launched=1, is_default=1).exclude(stock=0)
            else:
                queryset = LaunchedGoods.objects.filter(is_launched=1, is_default=1)
        else:
            if self.action == 'list':
                queryset = LaunchedGoods.objects.filter(is_launched=1).exclude(stock=0)
            else:
                queryset = LaunchedGoods.objects.filter(is_launched=1)
        if sort == '1':
            queryset = queryset.order_by('sales')
        elif sort == '2':
            queryset = queryset.order_by('-sales')
        elif sort == '3':
            queryset = queryset.order_by('price')
        elif sort == '4':
            queryset = queryset.order_by('-price')
        return queryset

    def get_serializer_class(self):
        if self.action == 'list':
            return LaunchedGoodsListModelSerializer
        else:
            return LaunchedGoodsRetrieveModelSerializer


class OrderInfoModelViewSet(ModelViewSet):
    '''订单'''

    pagination_class = MyPage
    filter_backends = (filters.SearchFilter, DjangoFilterBackend)
    search_fields = ('ordergoods__merchant__name', 'ordergoods__goods__name')
    filter_class = OrderInfoFilter

    def get_serializer_class(self):
        if self.action == 'list':
            return OrderInfoListModelSerializer
        else:
            return OrderInfoRetrieveModelSerializer

    def get_queryset(self):
        user = self.request.iser
        queryset = OrderInfo.objects.filter(customer_user_id=user.id).order_by('-create_time')
        return queryset

    def create(self, request, *args, **kwargs):
        user = self.request.iser
        goods_id = self.request.data.get('goods_id', None)
        count = self.request.data.get('count', None)
        voucher_id = self.request.data.get('voucher_id', None)
        name = self.request.data.get('name', None)
        identity = self.request.data.get('identity', None)
        check_identity = self.request.data.get('check_identity', None)
        level_id = self.request.data.get('level_id', None)
        reserved_mobile = self.request.data.get('reserved_mobile', None)
        point_array = self.request.data.get('point_array', None)
        if all([goods_id, count]) is False:
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            goods = Goods.objects.get(id=goods_id)
        except:
            return Response({'error': '无效商品id'}, status=status.HTTP_400_BAD_REQUEST)
        if goods.order_type == 2:
            if not all([name, identity, check_identity]):
                return Response({'error': '该下单商品需要提供收款信息'}, status=status.HTTP_400_BAD_REQUEST)
            if identity != check_identity:
                return Response({'error': '两次输入收款信息不一致'}, status=status.HTTP_400_BAD_REQUEST)
        elif goods.order_type == 1:
            if not level_id:
                return Response({'error': '该下单商品需要选择自提网点信息'}, status=status.HTTP_400_BAD_REQUEST)
            if not reserved_mobile:
                return Response({'error': '请填写预留手机号'}, status=status.HTTP_400_BAD_REQUEST)
            if not re.match(r'^1[3-9]\d{9}$', reserved_mobile):
                return Response({"error": "您输入的手机号格式不正确"}, status=status.HTTP_400_BAD_REQUEST)
            try:
                level = Level.objects.get(id=level_id)
                launchedgoods = LaunchedGoods.objects.filter(goods_id=goods_id, level_id=level_id).first()
                if not launchedgoods:
                    return Response({'error': '选择网点商品库存不足,请重新选择'}, status=status.HTTP_400_BAD_REQUEST)
            except:
                return Response({'error': '无效自提网点id'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            count = int(count)
        except Exception:
            return Response({'error': '参数count有误'}, status=status.HTTP_400_BAD_REQUEST)
        if goods.is_buymore == 0 and count != 1:
            return Response({'error': '当前商品不允许同时购买多件'}, status=status.HTTP_400_BAD_REQUEST)
        if goods.limit_by_user_count:
            buy_count = OrderGoods.objects.exclude(order__state=13).filter(order__customer_user_id=user.id, goods_id=goods.id).aggregate(Sum('count'))['count__sum']
            if buy_count:
                if buy_count >= goods.limit_by_user_count:
                    return Response({'error': '当前商品超出限购数量'}, status=status.HTTP_400_BAD_REQUEST)
        order_id = timezone.now().strftime('%Y%m%d%H%M%S') + ('%06d' % randint(0, 999999)) + ('%09d' % user.id)
        if voucher_id:
            try:
                alidiscounponinfo = AliDiscountCouponInfo.objects.get(voucher_id=voucher_id, alidiscountcoupon__coupon_channel=3, customer_user_id=user.id, status=1, gmt_expired__gte=datetime.datetime.now(), gmt_active__lte=datetime.datetime.now())
            except:
                return Response({'error': '优惠券选择有误,请返回重新选择'}, status=status.HTTP_400_BAD_REQUEST)
            alidiscountcoupon = alidiscounponinfo.alidiscountcoupon
            if alidiscountcoupon.coupon_type == 6:
                payable_amount = ((count-1) * goods.price)
            else:
                payable_amount = (count * goods.price) - alidiscounponinfo.total_amount
        else:
            payable_amount = (count * goods.price)
            alidiscounponinfo = None
        if point_array:
            try:
                point_set = ActivityData.objects.filter(id__in=point_array, state__in=[2, 3], customer_user=user, activity__available_begin_time__lte=datetime.datetime.now(), activity__available_end_time__gte=datetime.datetime.now()).order_by('activity__available_end_time')
            except:
                return Response({'error': '优惠券选择有误,请返回重新选择'}, status=status.HTTP_400_BAD_REQUEST)
        else:
            point_set = None
        # 显示的开启一个事务
        with transaction.atomic():
            # 创建事务保存点
            save_id = transaction.savepoint()

            # 暴力回滚
            try:
                # 保存订单基本信息OrderInfo(一)
                order_data = {}
                order_data['order_id'] = order_id
                order_data['customer_user_id'] = user.id
                order_data['create_time'] = datetime.datetime.now()
                order_data['total_count'] = count
                order_data['total_price'] = (count * goods.price)
                order_data['state'] = 1
                order_data['merchant_id'] = goods.merchant_id
                order_data['payable_amount'] = payable_amount
                order_data['reserved_mobile'] = reserved_mobile
                order_data['order_type'] = goods.order_type
                order_data['order_species'] = 2
                if level_id:
                    order_data['level_id'] = level_id
                order = OrderInfo.objects.create(**order_data)
                if alidiscounponinfo:
                    alidiscounponinfo.status = 8
                    alidiscounponinfo.order_id = order.id
                    alidiscounponinfo.save()
                if point_set:
                    select_point__sum = payable_amount * 100
                    point = Decimal('0')
                    date_now = datetime.datetime.now()
                    for activitydata in point_set:
                        if select_point__sum <= 0:
                            break
                        remain_point = activitydata.remain_point
                        if remain_point <= select_point__sum:
                            activitydata.state = 6
                            activitydata.remain_point = 0
                            activitydata.save()
                            user.point -= remain_point
                            user.save()
                            out_pointrecord_data = {}
                            out_pointrecord_data['customer_user_id'] = user.id
                            out_pointrecord_data['create_time'] = date_now
                            out_pointrecord_data['operate_type'] = 2
                            out_pointrecord_data['business_type'] = 2
                            out_pointrecord_data['point'] = remain_point
                            out_pointrecord_data['point_balance'] = user.point
                            out_pointrecord_data['remain_point'] = 0
                            out_pointrecord_data['order_id'] = order.id
                            out_pointrecord_data['activity_data_id'] = activitydata.id
                            PointRecord.objects.create(**out_pointrecord_data)
                            payable_amount -= (remain_point / 100)
                            point += remain_point
                        else:
                            activitydata.state = 3
                            activitydata.remain_point = remain_point - select_point__sum
                            activitydata.save()
                            user.point -= select_point__sum
                            user.save()
                            out_pointrecord_data = {}
                            out_pointrecord_data['customer_user_id'] = user.id
                            out_pointrecord_data['create_time'] = date_now
                            out_pointrecord_data['operate_type'] = 2
                            out_pointrecord_data['business_type'] = 2
                            out_pointrecord_data['point'] = select_point__sum
                            out_pointrecord_data['point_balance'] = user.point
                            out_pointrecord_data['remain_point'] = activitydata.remain_point
                            out_pointrecord_data['order_id'] = order.id
                            out_pointrecord_data['activity_data_id'] = activitydata.id
                            PointRecord.objects.create(**out_pointrecord_data)
                            payable_amount -= (select_point__sum / 100)
                            point += select_point__sum
                        select_point__sum -= remain_point
                    order.total_point = point
                    order.payable_amount = payable_amount
                    order.save()
                while True:
                    goods = Goods.objects.get(id=goods_id)
                    origin_stock = goods.stock
                    origin_sales = goods.sales
                    origin_remain_stock = goods.remain_stock
                    if level_id:
                        launchedgoods = LaunchedGoods.objects.filter(goods_id=goods_id, level_id=level_id).first()
                        if not launchedgoods:
                            return Response({'error': '库存不足'}, status=status.HTTP_400_BAD_REQUEST)
                        launched_origin_stock = launchedgoods.stock
                        launched_origin_sales = launchedgoods.sales
                        if count > launched_origin_stock:
                            transaction.savepoint_rollback(save_id)
                            return Response({'error': '库存不足'}, status=status.HTTP_400_BAD_REQUEST)
                        launchedgoods_id = launchedgoods.id
                        launched_new_stock = launched_origin_stock - count
                        launched_new_sales = launched_origin_sales + count
                        new_sales = origin_sales + count
                        new_remain_stock = origin_remain_stock - count
                        launched_result = LaunchedGoods.objects.filter(id=launchedgoods_id, stock=launched_origin_stock).update(stock=launched_new_stock, sales=launched_new_sales)
                        result = Goods.objects.filter(id=goods_id).update(sales=new_sales, remain_stock=new_remain_stock)
                        if launched_result == 0:
                            continue
                    else:
                        launchedgoods_id = None
                        if count > origin_stock:
                            transaction.savepoint_rollback(save_id)
                            return Response({'error': '库存不足'}, status=status.HTTP_400_BAD_REQUEST)
                        new_stock = origin_stock - count
                        new_sales = origin_sales + count
                        new_remain_stock = origin_remain_stock - count
                        result = Goods.objects.filter(id=goods_id, stock=origin_stock).update(stock=new_stock, sales=new_sales, remain_stock=new_remain_stock)
                        if result == 0:
                            continue
                    OrderGoods.objects.create(
                        order=order,
                        goods=goods,
                        count=count,
                        price=goods.price,
                        merchant_id=goods.merchant_id,
                        launched_goods_id=launchedgoods_id
                    )
                    break
                if goods.category_id == 3:
                    for i in range(count):
                        out_biz_no = f'100005{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
                        order_fund_trans_data = {}
                        order_fund_trans_data['out_biz_no'] = out_biz_no
                        order_fund_trans_data['exchange_amount'] = goods.exchange_amount
                        order_fund_trans_data['order_title'] = '支付宝积分网点兑活动'
                        if not all([name, identity, check_identity]):
                            order_fund_trans_data['identity'] = user.ali_user_id
                            order_fund_trans_data['identity_type'] = 1
                        else:
                            order_fund_trans_data['identity'] = identity
                            order_fund_trans_data['identity_type'] = 2
                            order_fund_trans_data['name'] = name
                        order_fund_trans_data['remark'] = ''
                        order_fund_trans_data['goods_id'] = goods.id
                        order_fund_trans_data['order_id'] = order.id
                        OrderFundTrans.objects.get_or_create(defaults=order_fund_trans_data, out_biz_no=out_biz_no)
            except Exception as e:
                logger.error(e)
                # 事务回滚
                transaction.savepoint_rollback(save_id)
                return Response({'error': '下单失败'}, status=status.HTTP_400_BAD_REQUEST)
        transaction.savepoint_commit(save_id)
        return Response({'success': '下单成功', 'order_id': order.id}, status=status.HTTP_200_OK)

    def update(self, request, *args, **kwargs):
        instance = self.get_object()
        user = self.request.iser
        HTTP_USER_AGENT = self.request.environ['HTTP_USER_AGENT']
        if instance.state != 1:
            return Response({'error': '订单状态错误'}, status=status.HTTP_400_BAD_REQUEST)
        if instance.payable_amount:
            if 'WeChat' in HTTP_USER_AGENT or 'MicroMessenger' in HTTP_USER_AGENT:
                is_new = self.request.is_new
                if is_new:
                    appid = settings.CUSTOMER_APP_ID_NEW
                    openid = user.new_openid
                else:
                    appid = settings.CUSTOMER_APP_ID
                    openid = user.openid
                data_json = {}
                data_json['appid'] = appid
                data_json['mchid'] = '1486198522'
                data_json['description'] = instance.ordergoods_set.all().first().goods.name
                data_json['out_trade_no'] = instance.order_id
                data_json['notify_url'] = 'https://api.sutpay.com/cpay/wx_result/'
                data_json['amount'] = {"total": int(instance.payable_amount*100)}
                data_json['payer'] = {"openid": openid}
                data_dict = pay_transactions_jsapi(data_json, appid)
                if 'code' in data_dict:
                    if data_dict['code'] not in ['OUT_TRADE_NO_USED', 'ORDER_NOT_EXIST', 'ORDER_CLOSED', 'INVALID_REQUEST']:
                        return Response({'error': data_dict['message']}, status=status.HTTP_400_BAD_REQUEST)
                    else:
                        order_id = timezone.now().strftime('%Y%m%d%H%M%S') + ('%06d' % randint(0, 999999)) + ('%09d' % user.id)
                        instance.order_id = order_id
                        instance.save()
                        data_json['out_trade_no'] = instance.order_id
                        data_dict = pay_transactions_jsapi(data_json, appid)
                        if 'code' in data_dict:
                            return Response({'error': data_dict['message']}, status=status.HTTP_400_BAD_REQUEST)
                instance.orderNum = data_dict['package'].replace('prepay_id=', '')
                instance.pay_type = 2
                instance.save()
                data_dict['order_id'] = instance.id
                data_dict['code'] = '0'
                return Response(data_dict, status=status.HTTP_200_OK)
            else:
                buyer_id = user.ali_user_id
                out_trade_no = instance.order_id
                total_amount = instance.payable_amount
                alipay_obj = AlipayOpen()
                description = instance.ordergoods_set.all().first().goods.name
                result = json.loads(alipay_obj.tradecreate(out_trade_no, total_amount, buyer_id, description))
                if result['code'] != '10000':
                    if result['sub_code'] != 'ACQ.TRADE_HAS_CLOSE':
                        return Response({'error': result['sub_msg']}, status=status.HTTP_400_BAD_REQUEST)
                    else:
                        order_id = timezone.now().strftime('%Y%m%d%H%M%S') + ('%06d' % randint(0, 999999)) + ('%09d' % user.id)
                        instance.order_id = order_id
                        instance.save()
                        result = json.loads(alipay_obj.tradecreate(order_id, total_amount, buyer_id, description))
                        if result['code'] != '10000':
                            return Response({'error': result['sub_msg']}, status=status.HTTP_400_BAD_REQUEST)
                instance.orderNum = result['trade_no']
                instance.pay_type = 1
                instance.save()
                return Response({'order_id': instance.id, 'trade_no': result['trade_no'], 'code': '0'}, status=status.HTTP_200_OK)
        else:
            orderNum = timezone.now().strftime('%Y%m%d%H%M%S') + ('%06d' % randint(0, 999999)) + ('%08d' % user.id)
            instance.orderNum = orderNum
            if instance.order_type == 1:
                instance.state = 2
            else:
                instance.state = 12
            instance.payment_time = datetime.datetime.now()
            instance.trade_no = orderNum
            instance.realpay_amount = 0
            instance.save()
            ordergoods_set = instance.ordergoods_set.all()
            for ordergoods in ordergoods_set:
                if ordergoods.goods.category_id == 2:
                    goodscoupons_set = GoodsCoupons.objects.filter(goods_id=ordergoods.goods_id, status=0)[:ordergoods.count]
                    for goodscoupons in goodscoupons_set:
                        goodscoupons.order_id = instance.id
                        goodscoupons.status = 1
                        goodscoupons.save()
                elif ordergoods.goods.category_id == 1:
                    for i in range(ordergoods.count):
                        while True:
                            coupons_id = '%16d' % randint(0, 9999999999999999)
                            goodscoupons = GoodsCoupons.objects.filter(coupons_id=coupons_id)
                            if not goodscoupons:
                                break
                        GoodsCoupons.objects.create(
                            coupons_id=coupons_id.replace(' ', ''),
                            status=1,
                            goods_id=ordergoods.goods_id,
                            order_id=instance.id,
                            validity_time=datetime.datetime.now()
                        )
                try:
                    if ordergoods.goods.is_settlement == 1:
                        receipts_time = datetime.datetime.now().strftime('%Y-%m-%d')
                        bill = MerchantBill.objects.filter(receipts_time=receipts_time, merchant_id=ordergoods.merchant_id).first()
                        if not bill:
                            bill_data = {}
                            bill_data['merchant_id'] = ordergoods.merchant_id
                            bill_data['receipts_time'] = receipts_time
                            bill_data['point'] = ordergoods.point
                            bill_data['amount'] = ordergoods.price * ordergoods.count
                            bill_data['payable_amount'] = ordergoods.price + Decimal(int(ordergoods.point)/100)
                            bill, create = MerchantBill.objects.get_or_create(defaults=bill_data, receipts_time=receipts_time, merchant_id=ordergoods.merchant_id)
                        else:
                            bill.point = bill.point + ordergoods.point
                            bill.amount = bill.amount + (ordergoods.price * ordergoods.count)
                            bill.payable_amount = bill.payable_amount + ordergoods.point + (ordergoods.price * ordergoods.count)
                            bill.save()
                        instance.bill_id = bill.id
                        instance.save()
                except:
                    pass
            try:
                orderfundtrans_set = instance.orderfundtrans_set.all().filter(status=1)
                for orderfundtrans in orderfundtrans_set:
                    alipay_obj = AlipayOpen()
                    trans_amount = str(orderfundtrans.exchange_amount)
                    order_title = orderfundtrans.order_title
                    out_biz_no = orderfundtrans.out_biz_no
                    identity = orderfundtrans.identity
                    if orderfundtrans.identity_type == 1:
                        result = json.loads(alipay_obj.transunitransfer_user_id(identity, out_biz_no, trans_amount, order_title))
                    else:
                        name = orderfundtrans.name
                        result = json.loads(alipay_obj.transunitransfer_login_id(identity, name, out_biz_no, trans_amount, order_title))
                    if result['code'] != '10000':
                        orderfundtrans.sub_msg = result['sub_msg']
                        orderfundtrans.status = 4
                        orderfundtrans.save()
                    else:
                        orderfundtrans.ali_order_id = result['order_id']
                        orderfundtrans.pay_fund_order_id = result['pay_fund_order_id']
                        orderfundtrans.trans_date = result['trans_date']
                        orderfundtrans.status = 2
                        orderfundtrans.save()
            except Exception as e:
                pass
            alidiscounponinfo_set = instance.alidiscountcouponinfo_set.all().filter(status=8)
            for voucher in alidiscounponinfo_set:
                activityinfo = voucher.alidiscountcoupon
                activityinfo.use_count += 1
                activityinfo.save()
                voucher.gmt_use = datetime.datetime.now()
                voucher.status = 7
                voucher.save()
                coupon_bill_data = {}
                coupon_bill_data['amount'] = instance.total_price
                coupon_bill_data['voucherinfo_id'] = voucher.id
                coupon_bill_data['biz_type'] = 'V_USE'
                coupon_bill_data['gmt_create'] = datetime.datetime.now()
                coupon_bill_data['status'] = 'S'
                coupon_bill_data['trade_no'] = orderNum
                AliDiscountCouponBillDetails.objects.create(**coupon_bill_data)
                try:
                    alidiscountcoupon_level = voucher.alidiscountcoupon_level
                    alidiscountcoupon_level.use_number += 1
                    alidiscountcoupon_level.p_use_number += 1
                    alidiscountcoupon_level.save()
                    relation_set = alidiscountcoupon_level.child_set.all()
                    for relation in relation_set:
                        parent = relation.parent
                        parent.p_use_number += 1
                        parent.save()
                    voucher_detail_data = {}
                    voucher_detail_data['v_type'] = 'COUPON'
                    voucher_detail_data['voucherId'] = voucher.voucher_id
                    voucher_detail_data['name'] = voucher.name
                    voucher_detail_data['otherContribute'] = instance.total_price
                    voucher_detail_data['merchantContribute'] = 0
                    voucher_detail_data['ali_order_id'] = instance.id
                    voucher_detail_data['amount'] = instance.total_price
                    VoucherDetail.objects.create(**voucher_detail_data)
                except:
                    pass
            return Response({'order_id': instance.id, 'trade_no': '', 'code': '1'}, status=status.HTTP_200_OK)

    def destroy(self, request, *args, **kwargs):
        user = self.request.iser
        instance = self.get_object()
        if instance.state != 1:
            return Response({'error': '订单状态错误'}, status=status.HTTP_400_BAD_REQUEST)
        ordergoods_set = instance.ordergoods_set.all()
        for ordergoods in ordergoods_set:
            goods = ordergoods.goods
            launched_goods = ordergoods.launched_goods
            count = ordergoods.count
            origin_sales = goods.sales
            new_sales = origin_sales - count
            goods.sales = new_sales
            goods.save()
            if launched_goods:
                launched_origin_stock = launched_goods.stock
                launched_origin_sales = launched_goods.sales
                launched_new_stock = launched_origin_stock + count
                launched_new_sales = launched_origin_sales - count
                launched_goods.stock = launched_new_stock
                launched_goods.sales = launched_new_sales
                launched_goods.save()
            else:
                origin_stock = goods.stock
                new_stock = origin_stock + count
                goods.stock = new_stock
                goods.save()
        instance.state = 13
        instance.cancel_time = datetime.datetime.now()
        instance.total_point = 0
        instance.save()
        alidiscounponinfo_set = instance.alidiscountcouponinfo_set.all().filter(status=8).update(status=1, order_id=None)
        try:
            pointrecord_set = instance.pointrecord_set.all()
            for pointrecord in pointrecord_set:
                activity_data = pointrecord.activity_data
                activity_data.remain_point += pointrecord.point
                activity_data.state = 3
                activity_data.save()
                user.point += pointrecord.point
                user.save()
                in_pointrecord_data = {}
                in_pointrecord_data['customer_user_id'] = user.id
                in_pointrecord_data['create_time'] = datetime.datetime.now()
                in_pointrecord_data['operate_type'] = 1
                in_pointrecord_data['business_type'] = 4
                in_pointrecord_data['point'] = pointrecord.point
                in_pointrecord_data['point_balance'] = user.point
                in_pointrecord_data['remain_point'] = activity_data.remain_point
                in_pointrecord_data['activity_data_id'] = activity_data.id
                in_pointrecord_data['order_id'] = instance.id
                PointRecord.objects.create(**in_pointrecord_data)
        except:
            pass
        return Response({'success': '取消订单成功'}, status=status.HTTP_200_OK)

    def preferential(self, request):
        user = self.request.iser
        goods_array = self.request.data.get('goods_array', None)
        voucher_id = self.request.data.get('voucher_id', None)
        point_array = self.request.data.get('point_array', None)
        if not goods_array:
            return Response({'error': '缺少商品信息'}, status=status.HTTP_400_BAD_REQUEST)
        goods_id_list = []
        try:
            total_point = Decimal('0')
            total_price = Decimal('0')
            max_price = Decimal('0')
            for goods_data in goods_array:
                goods = Goods.objects.get(id=goods_data['goods_id'])
                if goods.is_use_point == 1:
                    total_point += Decimal(int(goods_data['count'])) * 100 * goods.price
                total_price += Decimal(int(goods_data['count'])) * goods.price
                if goods.price > max_price:
                    max_price = goods.price
                goods_id_list.append(goods.id)
        except:
            return Response({'error': '无效商品id'}, status=status.HTTP_400_BAD_REQUEST)
        point_data = []
        voucher_list = []
        data = {}
        data['referential_price'] = Decimal('0')
        data['point_amount'] = Decimal('0')
        use_count = 0
        try:
            alidiscountcoupon_id_list = list(AliDiscountCouponGoodsAvailable.objects.filter(goods_id__in=goods_id_list).values_list('alidiscountcoupon_id', flat=True))
            alidiscountcouponinfo_set = AliDiscountCouponInfo.objects.filter(alidiscountcoupon__coupon_channel=3, customer_user_id=user.id, status=1, gmt_expired__gte=datetime.datetime.now(), gmt_active__lte=datetime.datetime.now()).order_by('-total_amount')
            if alidiscountcouponinfo_set:
                total_amount__max = alidiscountcouponinfo_set.filter(alidiscountcoupon_id__in=alidiscountcoupon_id_list).aggregate(Max('total_amount'))['total_amount__max']
                if total_amount__max > max_price:
                    select_alidiscountcouponinfo = alidiscountcouponinfo_set.filter(total_amount=total_amount__max,alidiscountcoupon_id__in=alidiscountcoupon_id_list).first()
                    data['referential_price'] = select_alidiscountcouponinfo.total_amount
                else:
                    select_alidiscountcouponinfo = alidiscountcouponinfo_set.filter(alidiscountcoupon__coupon_type=6,alidiscountcoupon_id__in=alidiscountcoupon_id_list).first()
                    if select_alidiscountcouponinfo:
                        data['referential_price'] = max_price
                    else:
                        select_alidiscountcouponinfo = alidiscountcouponinfo_set.filter(total_amount=total_amount__max,alidiscountcoupon_id__in=alidiscountcoupon_id_list).first()
                        data['referential_price'] = select_alidiscountcouponinfo.total_amount
                if voucher_id:
                    select_alidiscountcouponinfo1 = alidiscountcouponinfo_set.filter(voucher_id=voucher_id).first()
                    if select_alidiscountcouponinfo1:
                        if select_alidiscountcouponinfo1.alidiscountcoupon.coupon_type == 6:
                            data['referential_price'] = max_price
                        else:
                            data['referential_price'] = select_alidiscountcouponinfo1.total_amount
                        a = 1
                    else:
                        a = 0
                else:
                    a = 0
                for alidiscountcouponinfo in alidiscountcouponinfo_set:
                    r_data = {}
                    r_data['activity_name'] = alidiscountcouponinfo.alidiscountcoupon.activity_name
                    r_data['gmt_expired'] = alidiscountcouponinfo.gmt_expired.strftime('%Y-%m-%d %H:%M:%S')
                    r_data['floor_amount'] = alidiscountcouponinfo.alidiscountcoupon.floor_amount
                    coupon_type = alidiscountcouponinfo.alidiscountcoupon.coupon_type
                    if coupon_type == 9:
                        r_data['amount'] = alidiscountcouponinfo.total_amount
                    else:
                        r_data['amount'] = max_price
                    r_data['coupon_type'] = coupon_type
                    r_data['coupon_type_str'] = alidiscountcouponinfo.alidiscountcoupon.get_coupon_type_display()
                    r_data['voucher_id'] = alidiscountcouponinfo.voucher_id
                    if alidiscountcouponinfo.alidiscountcoupon_id in alidiscountcoupon_id_list:
                        r_data['is_choose'] = 1
                        use_count += 1
                    else:
                        r_data['is_choose'] = 0
                        r_data['reason'] = '限定商品可用'
                    if a == 1:
                        if alidiscountcouponinfo.voucher_id == voucher_id:
                            r_data['choose'] = 1
                        else:
                            r_data['choose'] = 0
                    else:
                        if alidiscountcouponinfo.id == select_alidiscountcouponinfo.id:
                            r_data['choose'] = 1
                        else:
                            r_data['choose'] = 0
                    if alidiscountcouponinfo.id == select_alidiscountcouponinfo.id:
                        voucher_list.insert(0, r_data)
                    else:
                        voucher_list.append(r_data)
        except:
            pass
        data['voucher_list'] = voucher_list
        data['voucher_count'] = use_count
        try:
            activitydata_set = ActivityData.objects.filter(state__in=[2, 3], customer_user=user, activity__available_begin_time__lte=datetime.datetime.now(), activity__available_end_time__gte=datetime.datetime.now()).order_by('activity__available_end_time')
            select_point = activitydata_set.filter(id__in=point_array)
            if select_point:
                select_point__sum = select_point.aggregate(Sum('remain_point'))['remain_point__sum']
                data['point_amount'] = select_point__sum / 100
            else:
                select_point__sum = 0
                data['point_amount'] = 0
            for activitydata in activitydata_set:
                r_data = ActivityDataListModelSerializer(activitydata).data
                if select_point__sum >= total_point:
                    r_data['is_choose'] = 0
                    data['point_amount'] = total_point / 100
                else:
                    r_data['is_choose'] = 1
                    data['point_amount'] = select_point__sum / 100
                if r_data['id'] in point_array:
                    r_data['choose'] = 1
                    r_data['is_choose'] = 1
                else:
                    r_data['choose'] = 0
                point_data.append(r_data)
        except:
            pass
        data['point_list'] = point_data
        return Response(data, status=status.HTTP_200_OK)


class CasrtsModelViewSet(ModelViewSet):

    def create(self, request, *args, **kwargs):
        goods_id = self.request.data.get('goods_id', None)
        count = self.request.data.get('count', None)


class SpeedLoanIndustryModelViewSet(ModelViewSet):

    queryset = SpeedLoanIndustry.objects.all()
    serializer_class = SpeedLoanIndustryModelSerializer
    filter_backends = (filters.SearchFilter, DjangoFilterBackend)
    search_fields = ('name', )


class SpeedLoanDrawModelViewSet(ModelViewSet):

    serializer_class = SpeedLoanDrawModelSerializer

    def get_queryset(self):
        user = self.request.iser
        return SpeedLoanDraw.objects.filter(customeruser_id=user.id)

    def lottery(self, request):
        user = self.request.iser
        speedloanuserinfo = SpeedLoanUserInfo.objects.filter(customeruser_id=user.id)
        if not speedloanuserinfo:
            return Response({'error': '用户尚未绑定实名信息,不能参与抽奖'}, status=status.HTTP_400_BAD_REQUEST)
        speedloandraw = SpeedLoanDraw.objects.filter(customeruser_id=user.id)
        if speedloandraw:
            return Response({'error': '每一个用户只能参与抽奖一次'}, status=status.HTTP_400_BAD_REQUEST)
        speedloandraw = SpeedLoanDraw.objects.filter(customeruser_id__isnull=True, payment_status=1).first()
        if speedloandraw:
            speedloandraw.customeruser_id = user.id
            speedloandraw.save()
            return Response({'success': '抽奖成功', 'gears': speedloandraw.gears, 'amount': speedloandraw.amount, 'id': speedloandraw.id, 'payment_status': speedloandraw.payment_status}, status=status.HTTP_200_OK)
        else:
            speedloandraw_data = {}
            speedloandraw_data['customeruser_id'] = user.id
            speedloandraw_data['amount'] = 0
            speedloandraw_data['partner_trade_no'] = '000000000000000000'
            speedloandraw_data['desc'] = '谢谢参与'
            speedloandraw_data['payment_status'] = 0
            speedloandraw_data['nonce_str'] = random_str()
            speedloandraw_data['gears'] = randint(1, 8)
            speedloandraw, create = SpeedLoanDraw.objects.get_or_create(defaults=speedloandraw_data, customeruser_id=user.id)
            return Response({'success': '抽奖成功', 'gears': speedloandraw.gears, 'amount': '谢谢参与', 'id': speedloandraw.id, 'payment_status': speedloandraw.payment_status}, status=status.HTTP_200_OK)

    def partial_update(self, request, *args, **kwargs):
        instance = self.get_object()
        user = self.request.iser
        if instance.payment_status != 1:
            return Response({'msg': '当前奖品状态不可领取', 'status': '400'}, status=status.HTTP_200_OK)
        params = {
            'mch_appid': settings.CUSTOMER_APP_ID,
            'mchid': '1486198522',  # 商户号
            'nonce_str': instance.nonce_str,
            'partner_trade_no': instance.partner_trade_no,
            'openid': user.openid,
            'check_name': 'NO_CHECK',
            'amount': int(instance.amount * 100),
            'desc': instance.desc
        }
        data_dict = mmpaymkttransfers(params)
        if data_dict['result_code'] == 'SUCCESS':
            instance.payment_time = data_dict['payment_time']
            instance.payment_no = data_dict['payment_no']
            instance.payment_status = 2
            instance.save()
            return Response({'msg': '请留意【微信支付】公众号-【商家转账入账通知】，如有疑问，请在【我的】页面 -【联系客服】', 'status': '200'}, status=status.HTTP_200_OK)
        else:
            if data_dict['err_code'] == 'AMOUNT_LIMIT':
                err_code_des = '被微信风控拦截，最低单笔付款限额调整为5元。'
                err_code = 10001
            elif data_dict['err_code'] == 'NOTENOUGH':
                err_code_des = '余额不足。'
                err_code = 10002
            elif data_dict['err_code'] == 'SYSTEMERROR':
                err_code_des = '微信内部接口调用发生错误。'
                err_code = 10003
            elif data_dict['err_code'] == 'NAME_MISMATCH':
                err_code_des = '收款人身份校验不通过。'
                err_code = 10004
            elif data_dict['err_code'] == 'FREQ_LIMIT':
                err_code_des = '接口请求频率超时接口限制。'
                err_code = 10005
            elif data_dict['err_code'] == 'MONEY_LIMIT':
                err_code_des = '已经达到今日付款总额上限/已达到付款给此用户额度上限。'
                err_code = 10006
            elif data_dict['err_code'] == 'V2_ACCOUNT_SIMPLE_BAN':
                err_code_des = '用户微信支付账户未知名，无法付款。'
                err_code = 10007
            elif data_dict['err_code'] == 'SENDNUM_LIMIT':
                err_code_des = '该用户今日付款次数超过限制'
                err_code_des1 = '该用户今日付款次数超过限制,如有需要请进入【微信支付商户平台-产品中心-企业付款到零钱-产品设置】进行修改。'
                err_code = 10008
            else:
                err_code_des = '其他未知错误。'
                err_code = 10009
            instance.return_msg = data_dict['err_code_des']
            instance.payment_status = 3
            instance.save()
            return Response({'msg': f'{err_code_des}', 'status': '400'}, status=status.HTTP_200_OK)


class LevelModelViewSet(ModelViewSet):

    serializer_class = LevelModelSerializer
    pagination_class = MyPage
    filter_backends = (filters.SearchFilter, DjangoFilterBackend)
    search_fields = ('name', )
    filter_class = LevelFilter

    def get_queryset(self):
        longitude = self.request.query_params.get('longitude', None)
        latitude = self.request.query_params.get('latitude', None)
        distance = self.request.query_params.get('distance', None)
        goods_id = self.request.query_params.get('goods_id', None)
        city_id = self.request.query_params.get('city_id', None)
        if not all([longitude, latitude]):
            queryset = Level.objects.filter(level=4)
        else:
            gcd_formula = "6371 * acos(least(greatest(cos(radians(%s)) * cos(radians(latitude)) * cos(radians(longitude) - radians(%s)) + sin(radians(%s)) * sin(radians(latitude)) , -1), 1))"
            sql = RawSQL(gcd_formula, (latitude, longitude, latitude))
            queryset = Level.objects.filter(level=4).annotate(distance=sql).order_by('distance')
            if distance:
                distance = int(distance) / 1000
                queryset = queryset.filter(distance__lt=distance)
        if goods_id:
            queryset = queryset.filter(launchedgoods__stock__gt=0, launchedgoods__is_launched=1, launchedgoods__goods_id=goods_id).distinct()
        return queryset

    def get_serializer_context(self):
        longitude = self.request.query_params.get('longitude', None)
        latitude = self.request.query_params.get('latitude', None)
        return {'longitude': longitude, 'latitude': latitude}

    def activity_city(self, request):
        queryset = Level.objects.exclude(id=35013017).filter(level=2, prov_id=7330)
        data = []
        for query in queryset:
            dic1 = {}
            dic1['name'] = query.name.replace('市分公司', '')
            dic1['id'] = query.id
            data.append(dic1)
        return Response(data, status=status.HTTP_200_OK)


class CashActivityDataModelViewSet(ModelViewSet):

    pagination_class = MyPage
    filter_backends = (filters.SearchFilter, DjangoFilterBackend)
    # filter_class = CashActivityDataFilter

    def get_serializer_class(self):
        if self.action == 'list':
            return CashActivityDataListModelSerializer
        else:
            return CashActivityDataRetrieveModelSerializer

    def get_queryset(self):
        user = self.request.iser
        queryset = CashActivityData.objects.filter(customer_user_id=user.id).order_by('-create_time')
        try:
            if '_mutable' in self.request.data.__dict__:
                self.request.data.__dict__['_mutable'] = True
        except:
            pass
        # self.request.data['use_count'] = str(queryset.filter(state__in=[2,3]).count())
        # self.request.data['not_use_count'] = str(queryset.exclude(state__in=[2,3]).count())
        return queryset

    def allow_cash(self, request):
        identify = self.request.query_params.get('identify', None)
        if not identify:
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            activity_data = CashActivityData.objects.get(identify=identify)
        except:
            return Response({'error': '无效二维码,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
        activity = activity_data.cash_activity
        data = {}
        data['activity_name'] = activity.name
        data['activity_type'] = activity.activity_type
        if activity.activity_type not in [3, 6]:
            data['amount'] = activity_data.amount
        else:
            if activity_data.state != 2:
                data['amount'] = '??'
            else:
                data['amount'] = activity_data.amount
        data['available_end_time'] = activity.available_end_time.strftime('%Y年%m月%d日 %H:%M:%S')
        data['state'] = activity_data.state
        if activity_data.state in [1, 2]:
            data['desc'] = '扫码领取后24小时到账微信零钱'
        elif activity_data.state == 3:
            data['desc'] = '如有疑问，请联系客户经理重新生成领取二维码'
        else:
            data['desc'] = activity_data.return_msg
        data['is_need_auth'] = 1
        data['activity_description'] = activity.activity_description
        data['is_psbc_card'] = activity.is_psbc_card
        date_now = datetime.datetime.now()
        today_time_begin = date_now.strftime('%Y-%m-%d 00:00:00')
        today_time_end = date_now.strftime('%Y-%m-%d 23:59:59')
        pay_type = 1
        if activity_data.amount > Decimal('100'):
            pay_type = 2
        encouragedraw = CashActivityData.objects.filter(received_time__gte=today_time_begin, received_time__lte=today_time_end, return_msg__contains='已达到今日商户付款额度上限')
        if encouragedraw:
            pay_type = 2
        if activity.is_wechat == 1:
            pay_type = 2
        data['pay_type'] = pay_type
        return Response(data, status=status.HTTP_200_OK)

    def receive_cash(self, request):
        user = self.request.iser
        identify = self.request.data.get('identify', None)
        login_id = self.request.data.get('login_id', None)
        realname = self.request.data.get('realname', None)
        if not all([identify]):
            return Response({'error': '缺少必传参数', 'status': ''}, status=status.HTTP_400_BAD_REQUEST)
        try:
            activity_data = CashActivityData.objects.get(identify=identify)
        except:
            return Response({'error': '无效二维码,请联系管理员', 'status': ''}, status=status.HTTP_400_BAD_REQUEST)
        if activity_data.state == 2:
            return Response({'error': '该二维码已经被领取', 'status': ''}, status=status.HTTP_400_BAD_REQUEST)
        if activity_data.state in [4, 3, 5]:
            return Response({'error': '该二维码已过期,请客户经理重新生成', 'status': ''}, status=status.HTTP_400_BAD_REQUEST)
        if activity_data.state != 1:
            return Response({'error': '该二维码已过期,请客户经理重新生成', 'status': ''}, status=status.HTTP_400_BAD_REQUEST)
        if user.is_auth != 2:
            return Response({'error': '请先完成实名认证', 'status': '1'}, status=status.HTTP_400_BAD_REQUEST)
        HTTP_USER_AGENT = self.request.environ['HTTP_USER_AGENT']
        date_now = datetime.datetime.now()
        cash_activity_id = activity_data.cash_activity_id
        cash_activity_level_id = activity_data.cash_activity_level_id
        activity = activity_data.cash_activity
        if activity.available_end_time <= datetime.datetime.now():
            return Response({'error': '活动已结束', 'status': ''}, status=status.HTTP_400_BAD_REQUEST)
        if activity.is_merchant == 1:
            check_merchant = Merchant.objects.filter(managermobile=user.mobile).first()
            if not check_merchant:
                if activity.is_white != 1:
                    return Response({'error': '您不是受邀请客户，请联系客户经理参与活动。', 'state': ''}, status=status.HTTP_400_BAD_REQUEST)
                else:
                    is_white = CashActivityWhiteTable.objects.filter(mobile=user.mobile, cashactivity_id=activity.id).first()
                    if not is_white:
                        return Response({'error': '您不是受邀请客户，请联系客户经理参与活动。', 'state': ''}, status=status.HTTP_400_BAD_REQUEST)
                    else:
                        white_table_data = {}
                        white_table_data['activitydata_id'] = activity_data.id
                        white_table_data['business_no'] = is_white.business_no
                        white_table_data['contact_name'] = is_white.contact_name
                        white_table_data['id_card_number'] = is_white.id_card_number
                        white_table_data['mobile'] = is_white.mobile
                        white_table_data['is_white_table'] = 1
                        CashActivityDataWhiteTable.objects.get_or_create(activitydata_id=activity_data.id, defaults=white_table_data)
            else:
                white_table_data = {}
                white_table_data['activitydata_id'] = activity_data.id
                white_table_data['business_no'] = check_merchant.wyfMerchantID
                white_table_data['contact_name'] = check_merchant.managerName
                white_table_data['id_card_number'] = check_merchant.identification_number
                white_table_data['mobile'] = check_merchant.managermobile
                white_table_data['is_white_table'] = 0
                CashActivityDataWhiteTable.objects.get_or_create(activitydata_id=activity_data.id, defaults=white_table_data)
        try:
            if activity.is_max_amount_by_customeruser == 1:
                max_amount_by_customeruser__sum = CashActivityData.objects.filter(cash_activity_id=activity.id, customer_user_id=user.id, state=2).aggregate(Sum('amount'))['amount__sum']
                if max_amount_by_customeruser__sum:
                    max_amount_by_customeruser__sum = Decimal(max_amount_by_customeruser__sum) + activity_data.amount
                    if max_amount_by_customeruser__sum > activity.max_amount_by_customeruser:
                        return Response({'error': f'当前用户领取额度已达上限,剩余可领取金额{activity.max_amount_by_customeruser-max_amount_by_customeruser__sum+activity_data.amount}', 'status': ''}, status=status.HTTP_400_BAD_REQUEST)
            if activity.is_check_identity == 1:
                check_manager = User.objects.filter(mobile=user.mobile, is_active=1)
                if check_manager:
                    return Response({'error': '该活动暂不允许内部员工领取，如有疑问请咨询客服。', 'status': ''}, status=status.HTTP_400_BAD_REQUEST)
        except:
            pass
        if 'WeChat' in HTTP_USER_AGENT or 'MicroMessenger' in HTTP_USER_AGENT:
            if all([login_id, realname]):
                activity_data.state = 5
                activity_data.save()
                alipay_obj = AlipayOpen()
                trans_amount = str(activity_data.amount)
                order_title = activity_data.desc
                out_biz_no = activity_data.partner_trade_no
                identity = user.ali_user_id
                activity_data.channel_id = activity.ali_channel_id
                if activity.ali_channel_id == 8:
                    result = json.loads(alipay_obj.transunitransfer_login_id_jiangxi88(login_id, realname, out_biz_no, trans_amount, order_title))
                elif activity.ali_channel_id == 11:
                    result = json.loads(alipay_obj.transunitransfer_login_id_jiangxi88_jizhangben(login_id, realname, out_biz_no, trans_amount, order_title))
                else:
                    result = json.loads(alipay_obj.transunitransfer_login_id(login_id, realname, out_biz_no, trans_amount, order_title))
                if result['code'] != '10000':
                    activity_data.return_msg = result['sub_msg']
                    activity_data.state = 3
                    activity_data.received_time = date_now
                    activity_data.customer_user_id = user.id
                    activity_data.mchid = 'alipay'
                    activity_data.mobile = user.mobile
                    activity_data.channel_id = activity.ali_channel_id
                    activity_data.login_id = login_id
                    activity_data.realname = realname
                    activity_data.save()
                    activity = activity_data.cash_activity
                    amount = activity_data.amount
                    if activity.activity_type in [1, 2, 3]:
                        while True:
                            activity_level = CashActivityLevel.objects.get(id=cash_activity_level_id)
                            origin_take_amount = activity_level.take_amount
                            origin_remain_amount = activity_level.remain_amount
                            origin_p_take_amount = activity_level.p_take_amount
                            origin_p_remain_amount = activity_level.p_remain_amount
                            new_take_amount = origin_take_amount - amount
                            new_remain_amount = origin_remain_amount + amount
                            new_p_take_amount = origin_p_take_amount - amount
                            new_p_remain_amount = origin_p_remain_amount + amount
                            result = CashActivityLevel.objects.filter(id=cash_activity_level_id, take_amount=origin_take_amount, remain_amount=origin_remain_amount, p_take_amount=origin_p_take_amount, p_remain_amount=origin_p_remain_amount).update(take_amount=new_take_amount, remain_amount=new_remain_amount, p_take_amount=new_p_take_amount, p_remain_amount=new_p_remain_amount)
                            if result == 0:
                                continue
                            break
                        while True:
                            activity = CashActivity.objects.get(id=cash_activity_id)
                            activity_origin_take_amount = activity.take_amount
                            activity_origin_remain_amount = activity.remain_amount
                            activity_new_take_amount = activity_origin_take_amount - amount
                            activity_new_remain_amount = activity_origin_remain_amount + amount
                            result = CashActivity.objects.filter(take_amount=activity_origin_take_amount, remain_amount=activity_origin_remain_amount, id=cash_activity_id).update(take_amount=activity_new_take_amount, remain_amount=activity_new_remain_amount)
                            if result == 0:
                                continue
                            break
                        relation_set = activity_level.child_set.all()
                        for relation in relation_set:
                            parent = relation.parent
                            parent.p_take_amount -= amount
                            parent.p_remain_amount += amount
                            parent.save()
                    else:
                        while True:
                            activity_level = CashActivityLevel.objects.get(id=cash_activity_level_id)
                            origin_take_amount = activity_level.take_amount
                            origin_max_amount = activity_level.max_amount
                            origin_p_take_amount = activity_level.p_take_amount
                            origin_p_max_amount = activity_level.p_max_amount
                            new_take_amount = origin_take_amount - amount
                            new_max_amount = origin_max_amount - amount
                            new_p_take_amount = origin_p_take_amount - amount
                            new_p_max_amount = origin_p_max_amount - amount
                            result = CashActivityLevel.objects.filter(id=cash_activity_level_id, take_amount=origin_take_amount, max_amount=origin_max_amount, p_take_amount=origin_p_take_amount, p_max_amount=origin_p_max_amount).update(take_amount=new_take_amount, max_amount=new_max_amount, p_take_amount=new_p_take_amount, p_max_amount=new_p_max_amount)
                            if result == 0:
                                continue
                            break
                        while True:
                            activity = CashActivity.objects.get(id=cash_activity_id)
                            activity_origin_take_amount = activity.take_amount
                            activity_origin_remain_amount = activity.remain_amount
                            activity_new_take_amount = activity_origin_take_amount - amount
                            activity_new_remain_amount = activity_origin_remain_amount + amount
                            result = CashActivity.objects.filter(take_amount=activity_origin_take_amount, remain_amount=activity_origin_remain_amount, id=cash_activity_id).update(take_amount=activity_new_take_amount, remain_amount=activity_new_remain_amount)
                            if result == 0:
                                continue
                            break
                        relation_set = activity_level.child_set.all()
                        for relation in relation_set:
                            parent = relation.parent
                            parent.p_take_amount -= amount
                            parent.p_max_amount -= amount
                            parent.save()
                    try:
                        cashactivitylevelrecord_data = {}
                        cashactivitylevelrecord_data['activity_level_id'] = activity_level.id
                        cashactivitylevelrecord_data['amount'] = amount
                        cashactivitylevelrecord_data['operation_type'] = 6
                        cashactivitylevelrecord_data['remain_amount'] = activity_level.remain_amount
                        cashactivitylevelrecord_data['p_remain_amount'] = activity_level.p_remain_amount
                        cashactivitylevelrecord_data['max_amount'] = activity_level.max_amount
                        cashactivitylevelrecord_data['p_max_amount'] = activity_level.p_max_amount
                        cashactivitylevelrecord_data['user_id'] = activity_data.companyuser_id
                        cashactivitylevelrecord_data['remark'] = '领取失败额度恢复'
                        cashactivitylevelrecord_data['activity_data_id'] = activity_data.id
                        cashactivitylevelrecord_data['activity_id'] = activity_level.cash_activity_id
                        CashActivityLevelRecord.objects.create(**cashactivitylevelrecord_data)
                        if activity.activity_type in [2, 5]:
                            cash_activity_rule = activity_data.cash_activity_rule
                            cash_activity_rule.probability += 1
                            cash_activity_rule.save()
                        if activity_data.task_id:
                            celery_app.control.revoke(activity_data.task_id)
                    except:
                        pass
                    return Response({'error': activity_data.return_msg, 'status': ''}, status=status.HTTP_400_BAD_REQUEST)
                else:
                    activity_data.received_time = result['trans_date']
                    activity_data.payment_no = result['pay_fund_order_id']
                    activity_data.customer_user_id = user.id
                    activity_data.mchid = 'alipay'
                    activity_data.state = 2
                    activity_data.mobile = user.mobile
                    activity_data.login_id = login_id
                    activity_data.realname = realname
                    activity_data.save()
                    while True:
                        activity_level = CashActivityLevel.objects.get(id=cash_activity_level_id)
                        origin_receive_amount = activity_level.receive_amount
                        origin_p_receive_amount = activity_level.p_receive_amount
                        new_receive_amount = origin_receive_amount + activity_data.amount
                        new_p_receive_amount = origin_p_receive_amount + activity_data.amount
                        result = CashActivityLevel.objects.filter(id=cash_activity_level_id, receive_amount=origin_receive_amount, p_receive_amount=origin_p_receive_amount).update(receive_amount=new_receive_amount, p_receive_amount=new_p_receive_amount)
                        if result == 0:
                            continue
                        break
                    while True:
                        activity = CashActivity.objects.get(id=cash_activity_id)
                        origin_distributed_amount = activity.distributed_amount
                        new_distributed_amount = origin_distributed_amount + activity_data.amount
                        result = CashActivity.objects.filter(id=cash_activity_id, distributed_amount=origin_distributed_amount).update(distributed_amount=new_distributed_amount)
                        if result == 0:
                            continue
                        break
                    relation_set = activity_level.child_set.all()
                    for relation in relation_set:
                        parent = relation.parent
                        parent.p_receive_amount += activity_data.amount
                        parent.save()
                    try:
                        if activity_data.task_id:
                            celery_app.control.revoke(activity_data.task_id)
                        if not user.level_id:
                            user.level_id = activity_level.level_id
                            user.user_id = activity_data.companyuser_id
                            user.save()
                        eta = datetime.datetime.utcnow() + datetime.timedelta(seconds=10)
                        capture_payeeFullName.apply_async(({"activityqrcode_id": activity_data.id},), eta=eta)
                    except:
                        pass
                    return Response({'success': '领取成功', 'status': ''}, status=status.HTTP_200_OK)
            else:
                if activity.is_wechat == 1:
                    return Response({'error': '当前活动暂不支持微信领取,请使用支付宝APP领取'}, status=status.HTTP_400_BAD_REQUEST)
                if user.new_openid:
                    appid = settings.CUSTOMER_APP_ID_NEW
                    openid = user.new_openid
                elif user.openid:
                    appid = settings.CUSTOMER_APP_ID
                    openid = user.openid
                else:
                    return Response({'error': '用户尚未关联微信,请使用微信【邮惠权益】小程序授权登录', 'status': ''}, status=status.HTTP_400_BAD_REQUEST)
                today_time_begin = datetime.datetime.now().strftime('%Y-%m-%d 00:00:00')
                today_time_end = datetime.datetime.now().strftime('%Y-%m-%d 23:59:59')
                encouragedraw = CashActivityData.objects.filter(received_time__gte=today_time_begin, received_time__lte=today_time_end, return_msg__contains='已达到今日商户付款额度上限')
                if encouragedraw:
                    return Response({'error': '微信额度已达到今日上限,请选择支付宝方式领取', 'status': ''}, status=status.HTTP_400_BAD_REQUEST)
                encouragedraw_set = CashActivityData.objects.filter(received_time__gte=today_time_begin, received_time__lte=today_time_end, customer_user_id=user.id, state=2)
                today_amount = Decimal('0')
                for encouragedraw in encouragedraw_set:
                    today_amount += encouragedraw.amount
                today_amount += activity_data.amount
                if today_amount > Decimal('100'):
                    return Response({'error': '微信额度已达到今日上限,请选择支付宝方式领取', 'status': ''}, status=status.HTTP_400_BAD_REQUEST)
                    mchid = '1571060401'
                    params = {
                        'mch_appid': appid,
                        'mchid': '1571060401',  # 商户号
                        'nonce_str': activity_data.nonce_str,
                        'partner_trade_no': activity_data.partner_trade_no,
                        'openid': openid,
                        'check_name': 'NO_CHECK',
                        'amount': int(activity_data.amount * 100),
                        'desc': activity_data.desc
                    }
                    data_dict = mmpaymkttransfers_xh(params)
                else:
                    activity_data.state = 5
                    activity_data.save()
                    mchid = '1486198522'
                    params = {
                        'mch_appid': appid,
                        'mchid': '1486198522',  # 商户号
                        'nonce_str': activity_data.nonce_str,
                        'partner_trade_no': activity_data.partner_trade_no,
                        'openid': openid,
                        'check_name': 'NO_CHECK',
                        'amount': int(activity_data.amount * 100),
                        'desc': activity_data.desc
                    }
                    data_dict = mmpaymkttransfers(params)
                if data_dict['result_code'] == 'SUCCESS':
                    activity_data.state = 2
                    activity_data.received_time = data_dict['payment_time']
                    activity_data.payment_no = data_dict['payment_no']
                    activity_data.customer_user_id = user.id
                    activity_data.mobile = user.mobile
                    activity_data.mchid = mchid
                    activity_data.channel_id = activity.wx_channel_id
                    activity_data.save()
                    while True:
                        activity_level = CashActivityLevel.objects.get(id=cash_activity_level_id)
                        origin_receive_amount = activity_level.receive_amount
                        origin_p_receive_amount = activity_level.p_receive_amount
                        new_receive_amount = origin_receive_amount + activity_data.amount
                        new_p_receive_amount = origin_p_receive_amount + activity_data.amount
                        result = CashActivityLevel.objects.filter(id=cash_activity_level_id, receive_amount=origin_receive_amount, p_receive_amount=origin_p_receive_amount).update(receive_amount=new_receive_amount, p_receive_amount=new_p_receive_amount)
                        if result == 0:
                            continue
                        break
                    while True:
                        activity = CashActivity.objects.get(id=cash_activity_id)
                        origin_distributed_amount = activity.distributed_amount
                        new_distributed_amount = origin_distributed_amount + activity_data.amount
                        result = CashActivity.objects.filter(id=cash_activity_id, distributed_amount=origin_distributed_amount).update(distributed_amount=new_distributed_amount)
                        if result == 0:
                            continue
                        break
                    relation_set = activity_level.child_set.all()
                    for relation in relation_set:
                        parent = relation.parent
                        parent.p_receive_amount += activity_data.amount
                        parent.save()
                    try:
                        if activity_data.task_id:
                            celery_app.control.revoke(activity_data.task_id)
                        if not user.level_id:
                            user.level_id = activity_level.level_id
                            user.user_id = activity_data.companyuser_id
                            user.save()
                    except:
                        pass
                    return Response({'success': '领取成功', 'status': ''}, status=status.HTTP_200_OK)
                else:
                    activity_data.return_msg = data_dict['err_code_des']
                    activity_data.state = 3
                    activity_data.received_time = date_now
                    activity_data.customer_user_id = user.id
                    activity_data.mchid = mchid
                    activity_data.mobile = user.mobile
                    activity_data.save()
                    activity = activity_data.cash_activity
                    amount = activity_data.amount
                    if activity.activity_type in [1, 2, 3]:
                        while True:
                            activity_level = CashActivityLevel.objects.get(id=cash_activity_level_id)
                            origin_take_amount = activity_level.take_amount
                            origin_remain_amount = activity_level.remain_amount
                            origin_p_take_amount = activity_level.p_take_amount
                            origin_p_remain_amount = activity_level.p_remain_amount
                            new_take_amount = origin_take_amount - amount
                            new_remain_amount = origin_remain_amount + amount
                            new_p_take_amount = origin_p_take_amount - amount
                            new_p_remain_amount = origin_p_remain_amount + amount
                            result = CashActivityLevel.objects.filter(id=cash_activity_level_id, take_amount=origin_take_amount,
                                                                      remain_amount=origin_remain_amount,
                                                                      p_take_amount=origin_p_take_amount,
                                                                      p_remain_amount=origin_p_remain_amount).update(
                                take_amount=new_take_amount, remain_amount=new_remain_amount, p_take_amount=new_p_take_amount,
                                p_remain_amount=new_p_remain_amount
                            )
                            if result == 0:
                                continue
                            break
                        while True:
                            activity = CashActivity.objects.get(id=cash_activity_id)
                            activity_origin_take_amount = activity.take_amount
                            activity_origin_remain_amount = activity.remain_amount
                            activity_new_take_amount = activity_origin_take_amount - amount
                            activity_new_remain_amount = activity_origin_remain_amount + amount
                            result = CashActivity.objects.filter(take_amount=activity_origin_take_amount, remain_amount=activity_origin_remain_amount, id=cash_activity_id).update(
                                take_amount=activity_new_take_amount, remain_amount=activity_new_remain_amount)
                            if result == 0:
                                continue
                            break
                        relation_set = activity_level.child_set.all()
                        for relation in relation_set:
                            parent = relation.parent
                            parent.p_take_amount -= amount
                            parent.p_remain_amount += amount
                            parent.save()
                    else:
                        while True:
                            activity_level = CashActivityLevel.objects.get(id=cash_activity_level_id)
                            origin_take_amount = activity_level.take_amount
                            origin_max_amount = activity_level.max_amount
                            origin_p_take_amount = activity_level.p_take_amount
                            origin_p_max_amount = activity_level.p_max_amount
                            new_take_amount = origin_take_amount - amount
                            new_max_amount = origin_max_amount - amount
                            new_p_take_amount = origin_p_take_amount - amount
                            new_p_max_amount = origin_p_max_amount - amount
                            result = CashActivityLevel.objects.filter(id=cash_activity_level_id, take_amount=origin_take_amount,
                                                                      max_amount=origin_max_amount,
                                                                      p_take_amount=origin_p_take_amount,
                                                                      p_max_amount=origin_p_max_amount).update(
                                take_amount=new_take_amount, max_amount=new_max_amount, p_take_amount=new_p_take_amount,
                                p_max_amount=new_p_max_amount
                            )
                            if result == 0:
                                continue
                            break
                        while True:
                            activity = CashActivity.objects.get(id=cash_activity_id)
                            activity_origin_take_amount = activity.take_amount
                            activity_origin_remain_amount = activity.remain_amount
                            activity_new_take_amount = activity_origin_take_amount - amount
                            activity_new_remain_amount = activity_origin_remain_amount + amount
                            result = CashActivity.objects.filter(take_amount=activity_origin_take_amount, remain_amount=activity_origin_remain_amount, id=cash_activity_id).update(
                                take_amount=activity_new_take_amount, remain_amount=activity_new_remain_amount)
                            if result == 0:
                                continue
                            break
                        relation_set = activity_level.child_set.all()
                        for relation in relation_set:
                            parent = relation.parent
                            parent.p_take_amount -= amount
                            parent.p_max_amount -= amount
                            parent.save()
                    try:
                        cashactivitylevelrecord_data = {}
                        cashactivitylevelrecord_data['activity_level_id'] = activity_level.id
                        cashactivitylevelrecord_data['amount'] = amount
                        cashactivitylevelrecord_data['operation_type'] = 6
                        cashactivitylevelrecord_data['remain_amount'] = activity_level.remain_amount
                        cashactivitylevelrecord_data['p_remain_amount'] = activity_level.p_remain_amount
                        cashactivitylevelrecord_data['max_amount'] = activity_level.max_amount
                        cashactivitylevelrecord_data['p_max_amount'] = activity_level.p_max_amount
                        cashactivitylevelrecord_data['user_id'] = activity_data.companyuser_id
                        cashactivitylevelrecord_data['remark'] = '领取失败额度恢复'
                        cashactivitylevelrecord_data['activity_data_id'] = activity_data.id
                        cashactivitylevelrecord_data['activity_id'] = activity_level.cash_activity_id
                        CashActivityLevelRecord.objects.create(**cashactivitylevelrecord_data)
                        if activity.activity_type in [2, 5]:
                            cash_activity_rule = activity_data.cash_activity_rule
                            cash_activity_rule.probability += 1
                            cash_activity_rule.save()
                        if activity_data.task_id:
                            celery_app.control.revoke(activity_data.task_id)
                    except:
                        pass
                    return Response({'error': data_dict['err_code_des'], 'status': ''}, status=status.HTTP_400_BAD_REQUEST)
        else:
            if not user.ali_user_id:
                return Response({'error': '用户尚未关联支付宝,请使用支付宝【邮惠权益】小程序授权登录'}, status=status.HTTP_400_BAD_REQUEST)
            if activity.is_psbc_card == 1:
                return Response({'error': '活动暂时不支持支付宝领取,请使用微信领取'}, status=status.HTTP_400_BAD_REQUEST)
            activity_data.state = 5
            activity_data.save()
            alipay_obj = AlipayOpen()
            trans_amount = str(activity_data.amount)
            order_title = activity_data.desc
            out_biz_no = activity_data.partner_trade_no
            identity = user.ali_user_id
            activity_data.channel_id = activity.ali_channel_id
            if activity.ali_channel_id == 8:
                result = json.loads(alipay_obj.transunitransfer_user_id_jiangxi88(identity, out_biz_no, trans_amount, order_title))
            elif activity.ali_channel_id == 11:
                result = json.loads(alipay_obj.transunitransfer_user_id_jiangxi88_jizhangben(identity, out_biz_no, trans_amount, order_title))
            else:
                result = json.loads(alipay_obj.transunitransfer_user_id(identity, out_biz_no, trans_amount, order_title))
            if result['code'] != '10000':
                activity_data.return_msg = result['sub_msg']
                activity_data.state = 3
                activity_data.received_time = date_now
                activity_data.customer_user_id = user.id
                activity_data.mchid = 'alipay'
                activity_data.mobile = user.mobile
                activity_data.channel_id = activity.ali_channel_id
                activity_data.save()
                activity = activity_data.cash_activity
                amount = activity_data.amount
                if activity.activity_type in [1, 2, 3]:
                    while True:
                        activity_level = CashActivityLevel.objects.get(id=cash_activity_level_id)
                        origin_take_amount = activity_level.take_amount
                        origin_remain_amount = activity_level.remain_amount
                        origin_p_take_amount = activity_level.p_take_amount
                        origin_p_remain_amount = activity_level.p_remain_amount
                        new_take_amount = origin_take_amount - amount
                        new_remain_amount = origin_remain_amount + amount
                        new_p_take_amount = origin_p_take_amount - amount
                        new_p_remain_amount = origin_p_remain_amount + amount
                        result = CashActivityLevel.objects.filter(id=cash_activity_level_id, take_amount=origin_take_amount,
                                                                  remain_amount=origin_remain_amount,
                                                                  p_take_amount=origin_p_take_amount,
                                                                  p_remain_amount=origin_p_remain_amount).update(
                            take_amount=new_take_amount, remain_amount=new_remain_amount, p_take_amount=new_p_take_amount,
                            p_remain_amount=new_p_remain_amount
                        )
                        if result == 0:
                            continue
                        break
                    while True:
                        activity = CashActivity.objects.get(id=cash_activity_id)
                        activity_origin_take_amount = activity.take_amount
                        activity_origin_remain_amount = activity.remain_amount
                        activity_new_take_amount = activity_origin_take_amount - amount
                        activity_new_remain_amount = activity_origin_remain_amount + amount
                        result = CashActivity.objects.filter(take_amount=activity_origin_take_amount, remain_amount=activity_origin_remain_amount, id=cash_activity_id).update(
                            take_amount=activity_new_take_amount, remain_amount=activity_new_remain_amount)
                        if result == 0:
                            continue
                        break
                    relation_set = activity_level.child_set.all()
                    for relation in relation_set:
                        parent = relation.parent
                        parent.p_take_amount -= amount
                        parent.p_remain_amount += amount
                        parent.save()
                else:
                    while True:
                        activity_level = CashActivityLevel.objects.get(id=cash_activity_level_id)
                        origin_take_amount = activity_level.take_amount
                        origin_max_amount = activity_level.max_amount
                        origin_p_take_amount = activity_level.p_take_amount
                        origin_p_max_amount = activity_level.p_max_amount
                        new_take_amount = origin_take_amount - amount
                        new_max_amount = origin_max_amount - amount
                        new_p_take_amount = origin_p_take_amount - amount
                        new_p_max_amount = origin_p_max_amount - amount
                        result = CashActivityLevel.objects.filter(id=cash_activity_level_id, take_amount=origin_take_amount,
                                                                  max_amount=origin_max_amount,
                                                                  p_take_amount=origin_p_take_amount,
                                                                  p_max_amount=origin_p_max_amount).update(
                            take_amount=new_take_amount, max_amount=new_max_amount, p_take_amount=new_p_take_amount,
                            p_max_amount=new_p_max_amount
                        )
                        if result == 0:
                            continue
                        break
                    while True:
                        activity = CashActivity.objects.get(id=cash_activity_id)
                        activity_origin_take_amount = activity.take_amount
                        activity_origin_remain_amount = activity.remain_amount
                        activity_new_take_amount = activity_origin_take_amount - amount
                        activity_new_remain_amount = activity_origin_remain_amount + amount
                        result = CashActivity.objects.filter(take_amount=activity_origin_take_amount, remain_amount=activity_origin_remain_amount, id=cash_activity_id).update(
                            take_amount=activity_new_take_amount, remain_amount=activity_new_remain_amount)
                        if result == 0:
                            continue
                        break
                    relation_set = activity_level.child_set.all()
                    for relation in relation_set:
                        parent = relation.parent
                        parent.p_take_amount -= amount
                        parent.p_max_amount -= amount
                        parent.save()
                try:
                    cashactivitylevelrecord_data = {}
                    cashactivitylevelrecord_data['activity_level_id'] = activity_level.id
                    cashactivitylevelrecord_data['amount'] = amount
                    cashactivitylevelrecord_data['operation_type'] = 6
                    cashactivitylevelrecord_data['remain_amount'] = activity_level.remain_amount
                    cashactivitylevelrecord_data['p_remain_amount'] = activity_level.p_remain_amount
                    cashactivitylevelrecord_data['max_amount'] = activity_level.max_amount
                    cashactivitylevelrecord_data['p_max_amount'] = activity_level.p_max_amount
                    cashactivitylevelrecord_data['user_id'] = activity_data.companyuser_id
                    cashactivitylevelrecord_data['remark'] = '领取失败额度恢复'
                    cashactivitylevelrecord_data['activity_data_id'] = activity_data.id
                    cashactivitylevelrecord_data['activity_id'] = activity_level.cash_activity_id
                    CashActivityLevelRecord.objects.create(**cashactivitylevelrecord_data)
                    if activity.activity_type in [2, 5]:
                        cash_activity_rule = activity_data.cash_activity_rule
                        cash_activity_rule.probability += 1
                        cash_activity_rule.save()
                    if activity_data.task_id:
                        celery_app.control.revoke(activity_data.task_id)
                except:
                    pass
                return Response({'error': activity_data.return_msg, 'status': ''}, status=status.HTTP_400_BAD_REQUEST)
            else:
                activity_data.received_time = result['trans_date']
                activity_data.payment_no = result['pay_fund_order_id']
                activity_data.customer_user_id = user.id
                activity_data.mchid = 'alipay'
                activity_data.state = 2
                activity_data.mobile = user.mobile
                activity_data.save()
                while True:
                    activity_level = CashActivityLevel.objects.get(id=cash_activity_level_id)
                    origin_receive_amount = activity_level.receive_amount
                    origin_p_receive_amount = activity_level.p_receive_amount
                    new_receive_amount = origin_receive_amount + activity_data.amount
                    new_p_receive_amount = origin_p_receive_amount + activity_data.amount
                    result = CashActivityLevel.objects.filter(id=cash_activity_level_id, receive_amount=origin_receive_amount, p_receive_amount=origin_p_receive_amount).update(receive_amount=new_receive_amount, p_receive_amount=new_p_receive_amount)
                    if result == 0:
                        continue
                    break
                while True:
                    activity = CashActivity.objects.get(id=cash_activity_id)
                    origin_distributed_amount = activity.distributed_amount
                    new_distributed_amount = origin_distributed_amount + activity_data.amount
                    result = CashActivity.objects.filter(id=cash_activity_id, distributed_amount=origin_distributed_amount).update(distributed_amount=new_distributed_amount)
                    if result == 0:
                        continue
                    break
                relation_set = activity_level.child_set.all()
                for relation in relation_set:
                    parent = relation.parent
                    parent.p_receive_amount += activity_data.amount
                    parent.save()
                try:
                    if activity_data.task_id:
                        celery_app.control.revoke(activity_data.task_id)
                    if not user.level_id:
                        user.level_id = activity_level.level_id
                        user.user_id = activity_data.companyuser_id
                        user.save()
                    eta = datetime.datetime.utcnow() + datetime.timedelta(seconds=10)
                    capture_payeeFullName.apply_async(({"activityqrcode_id": activity_data.id},), eta=eta)
                except:
                    pass
                return Response({'success': '领取成功', 'status': ''}, status=status.HTTP_200_OK)


class CustomizeActivityFlipCARDS1ModelViewSet(ModelViewSet):

    pagination_class = MyPage
    filter_backends = (filters.SearchFilter, DjangoFilterBackend)
    filter_class = CustomizeActivityFlipCARDSFilter

    def get_serializer_class(self):
        if self.action == 'list':
            return CustomizeActivityFlipCARDSListModelSerializer
        else:
            return CustomizeActivityFlipCARDSRetrieveModelSerializer

    def get_queryset(self):
        user = self.request.iser
        if self.action == 'list':
            queryset = CustomizeActivityFlipCARDS.objects.filter(user_id=user.id, open_status__in=[2, 4, 6], customizeactivity__activity_type=11)
        else:
            queryset = CustomizeActivityFlipCARDS.objects.filter(user_id=user.id)
        return queryset.order_by('-id')

    def update(self, request, *args, **kwargs):
        instance = self.get_object()
        if instance.open_status != 2:
            return Response({'error': '重复领取'}, status=status.HTTP_400_BAD_REQUEST)
        distribute_couponbag.delay({"filp_id": instance.id})
        return Response({'success': '操作成功,等待后台派发'}, status=status.HTTP_200_OK)


class CustomizeActivityFlipCARDSModelViewSet(ModelViewSet):

    # pagination_class = MyPage
    filter_backends = (filters.SearchFilter, DjangoFilterBackend)

    def get_serializer_class(self):
        if self.action == 'list':
            return CustomizeActivityFlipCARDSListModelSerializer
        else:
            return CustomizeActivityFlipCARDSRetrieveModelSerializer

    def get_queryset(self):
        user = self.request.iser
        if self.action == 'list':
            customizeactivity_id = self.request.query_params.get('customizeactivity_id', None)
            if customizeactivity_id:
                queryset = CustomizeActivityFlipCARDS.objects.filter(user_id=user.id, open_status__in=[2, 4, 6], customizeactivity_id=customizeactivity_id)
            else:
                queryset = CustomizeActivityFlipCARDS.objects.filter(user_id=user.id, open_status__in=[2, 4, 6], id=1)
        else:
            queryset = CustomizeActivityFlipCARDS.objects.filter(user_id=user.id)
        return queryset

    def allow_customize(self, request):
        user = self.request.iser
        identify = self.request.query_params.get('identify', None)
        if not identify:
            return Response({'error': '缺少必传参数', 'state': '1'}, status=status.HTTP_400_BAD_REQUEST)
        if len(identify) == 48:
            try:
                customizeactivitylevel = None
                customizeactivity = CustomizeActivity.objects.get(identify=identify)
                level = customizeactivity.level
            except:
                return Response({'error': '无效二维码,请联系管理员', 'state': '1'}, status=status.HTTP_400_BAD_REQUEST)
        else:
            try:
                customizeactivitylevel = CustomizeActivityLevel.objects.get(identify=identify)
                customizeactivity = customizeactivitylevel.customizeactivity
                level = customizeactivitylevel.level
            except:
                return Response({'error': '无效二维码,请联系管理员', 'state': '1'}, status=status.HTTP_400_BAD_REQUEST)
        if customizeactivity.is_white == 1:
            is_white = CustomizeActivityWhiteTable.objects.filter(mobile=user.mobile, customizeactivity_id=customizeactivity.id)
            if not is_white:
                return Response({'error': '您不是受邀请客户，请联系客户经理参与活动。', 'state': '2', 'activity_name': customizeactivity.activity_name}, status=status.HTTP_400_BAD_REQUEST)
        if user.is_auth != 2 and customizeactivity.is_need_auth == 1:
            state_1 = "0"
        else:
            state_1 = ""
        #     return Response({'error': '请先完成实名认证', 'state': '0'}, status=status.HTTP_400_BAD_REQUEST)
        if customizeactivity.activity_status == 2:
            return Response({'error': '活动尚未开始,敬请期待', 'state': '1', 'activity_name': customizeactivity.activity_name}, status=status.HTTP_400_BAD_REQUEST)
        if customizeactivity.activity_status != 1:
            return Response({'error': '活动已经结束,敬请期待下一次活动', 'state': '1', 'activity_name': customizeactivity.activity_name}, status=status.HTTP_400_BAD_REQUEST)
        if customizeactivity.is_draw_code == 1:
            redis_conn = get_redis_connection("default")
            prize_draw = redis_conn.get("prize_draw_%s" % user.id)
            if prize_draw:
                cut_off_time = prize_draw.decode()
                is_cut_off_time = 1
            else:
                cut_off_time = ''
                is_cut_off_time = 0
        else:
            cut_off_time = ''
            is_cut_off_time = 0
        if customizeactivity.activity_type == 1:
            queryset = CustomizeActivityFlipCARDS.objects.filter(user=user, customizeactivity_id=customizeactivity.id)
            if not queryset:
                try:
                    customizeactivity.join_user_count += 1
                    customizeactivity.save()
                    if customizeactivitylevel:
                        customizeactivitylevel.join_user_count += 1
                        customizeactivitylevel.save()
                except:
                    pass
                x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
                customizeactivityrules_set = customizeactivity.customizeactivityrules_set.all()
                shuffle(x)
                randint_choices = {
                    1: False,
                    2: False,
                    3: False,
                    4: False,
                    5: False,
                    6: False,
                    7: False,
                    8: False,
                    9: False
                }
                a = 1
                for customizeactivityrules in customizeactivityrules_set:
                    for i in range(a, a+customizeactivityrules.count):
                        randint_choices[i] = customizeactivityrules
                    a += customizeactivityrules.count
                for i in x:
                    identify = f'100003{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
                    data = dict()
                    data['identify'] = identify
                    data['user_id'] = user.id
                    data['mobile'] = user.mobile
                    data['gears'] = i
                    data['customizeactivity_id'] = customizeactivity.id
                    data['level_id'] = level.id
                    if randint_choices[i]:
                        if randint_choices[i].prize_type in [1, 2]:
                            data['alidiscountcoupon_id'] = randint_choices[i].alidiscountcoupon_id
                            data['win_type'] = randint_choices[i].prize_type
                        else:
                            data['cashactivity_id'] = randint_choices[i].cashactivity_id
                            data['win_type'] = randint_choices[i].prize_type
                    CustomizeActivityFlipCARDS.objects.get_or_create(defaults=data, gears=i, user_id=user.id, customizeactivity_id=customizeactivity.id)
                queryset = CustomizeActivityFlipCARDS.objects.filter(user=user, customizeactivity_id=customizeactivity.id)
            data = {}
            data['lists'] = CustomizeActivityFlipCARDSRetrieveModelSerializer(queryset, many=True).data
            data['count'] = customizeactivity.lucky_count_by_user - queryset.exclude(open_status__in=[1, 5]).count()
            data['activity_description'] = customizeactivity.activity_description
            data['is_business_form'] = customizeactivity.is_business_form
            data['id'] = customizeactivity.id
            data['state'] = state_1
            data['activity_name'] = customizeactivity.activity_name
            data['available_time'] = f'{customizeactivity.available_begin_time.strftime("%Y.%m.%d %H:%M:%S")}-{customizeactivity.available_end_time.strftime("%Y.%m.%d %H:%M:%S")}'
            return Response(data, status=status.HTTP_200_OK)
        elif customizeactivity.activity_type in [2, 4]:
            queryset = CustomizeActivityFlipCARDS.objects.filter(user=user, customizeactivity_id=customizeactivity.id)
            customizeactivityrules_set = customizeactivity.customizeactivityrules_set.all()
            check_customizeactivityrules_set = customizeactivityrules_set.filter(Q(alidiscountcoupon__remain_number__gt=0) | Q(cashactivity__remain_amount__gt=0) | Q(prize_type=4))
            data = {}
            lists = CustomizeActivityRulesListModelSerializer(customizeactivityrules_set, many=True).data
            if not check_customizeactivityrules_set:
                lists[-1] = {
                    "id": "X",
                    "prize_type": 4,
                    "prize_type_str": '谢谢参与',
                    "activity_info": {
                        "id": "",
                        "activity_name": "",
                        "activity_id": "",
                        "rule": "",
                        "available_begin_time": '',
                        "available_end_time": '',
                        "amount": ''
                    }
                }
            data['lists'] = lists
            data['count'] = customizeactivity.lucky_count_by_user - queryset.count()
            data['activity_description'] = customizeactivity.activity_description
            data['is_business_form'] = customizeactivity.is_business_form
            data['id'] = customizeactivity.id
            data['state'] = state_1
            data['activity_name'] = customizeactivity.activity_name
            data['is_draw_code'] = customizeactivity.is_draw_code
            data['cut_off_time'] = cut_off_time
            data['is_cut_off_time'] = is_cut_off_time
            data['available_time'] = f'{customizeactivity.available_begin_time.strftime("%Y.%m.%d %H:%M:%S")}-{customizeactivity.available_end_time.strftime("%Y.%m.%d %H:%M:%S")}'
            return Response(data, status=status.HTTP_200_OK)
        else:
            return Response({'error': '无效活动类型'}, status=status.HTTP_400_BAD_REQUEST)

    def turnplate(self, request):
        user = self.request.iser
        identify = self.request.query_params.get('identify', None)
        business_name = self.request.query_params.get('business_name', None)
        business_account = self.request.query_params.get('business_account', None)
        business_amount = self.request.query_params.get('business_amount', None)
        business_type = self.request.query_params.get('business_type', None)
        draw_code = self.request.query_params.get('draw_code', None)
        if not identify:
            return Response({'error': '缺少必传参数', 'state': '1'}, status=status.HTTP_400_BAD_REQUEST)
        if len(identify) == 48:
            try:
                customizeactivitylevel = None
                customizeactivity = CustomizeActivity.objects.get(identify=identify)
                level = customizeactivity.level
            except:
                return Response({'error': '无效二维码,请联系管理员', 'state': '1'}, status=status.HTTP_400_BAD_REQUEST)
        else:
            try:
                customizeactivitylevel = CustomizeActivityLevel.objects.get(identify=identify)
                customizeactivity = customizeactivitylevel.customizeactivity
                level = customizeactivitylevel.level
            except:
                return Response({'error': '无效二维码,请联系管理员', 'state': '1'}, status=status.HTTP_400_BAD_REQUEST)
        if customizeactivity.is_white == 1:
            is_white = CustomizeActivityWhiteTable.objects.filter(mobile=user.mobile, customizeactivity_id=customizeactivity.id)
            if not is_white:
                return Response({'error': '您不是受邀请客户，请联系客户经理参与活动。', 'state': '2', 'activity_name': customizeactivity.activity_name}, status=status.HTTP_400_BAD_REQUEST)
        if customizeactivity.is_business_form == 1:
            if not all([business_name, business_account, business_amount, business_type]):
                return Response({'error': '请上传业务表单信息', 'state': '2', 'activity_name': customizeactivity.activity_name}, status=status.HTTP_400_BAD_REQUEST)
            if len(business_account) != 4:
                return Response({'error': '业务账号格式有误', 'state': '2', 'activity_name': customizeactivity.activity_name}, status=status.HTTP_400_BAD_REQUEST)
            if str(business_type) not in ['1', '2', '3']:
                return Response({'error': '业务类型有误', 'state': '2', 'activity_name': customizeactivity.activity_name}, status=status.HTTP_400_BAD_REQUEST)
            try:
                business_amount = Decimal(business_amount)
            except:
                return Response({'error': '业务金额有误', 'state': '2', 'activity_name': customizeactivity.activity_name}, status=status.HTTP_400_BAD_REQUEST)
        if user.is_auth != 2 and customizeactivity.is_need_auth == 1:
            return Response({'error': '请先完成实名认证', 'state': '0'}, status=status.HTTP_400_BAD_REQUEST)
        if customizeactivity.available_begin_time > datetime.datetime.now():
            return Response({'error': '活动尚未开始,敬请期待', 'state': '1', 'activity_name': customizeactivity.activity_name}, status=status.HTTP_400_BAD_REQUEST)
        if customizeactivity.activity_status == 2:
            return Response({'error': '活动已经结束,敬请期待下一次活动', 'state': '1', 'activity_name': customizeactivity.activity_name}, status=status.HTTP_400_BAD_REQUEST)
        if customizeactivity.available_end_time < datetime.datetime.now():
            customizeactivity.activity_status = 2
            customizeactivity.save()
            return Response({'error': '活动已经结束,敬请期待下一次活动', 'state': '1', 'activity_name': customizeactivity.activity_name}, status=status.HTTP_400_BAD_REQUEST)
        if customizeactivity.activity_status != 1:
            return Response({'error': '活动尚未开始,敬请期待', 'state': '1', 'activity_name': customizeactivity.activity_name}, status=status.HTTP_400_BAD_REQUEST)
        if customizeactivity.lucky_count_by_user <= CustomizeActivityFlipCARDS.objects.filter(user_id=user.id, customizeactivity=customizeactivity).count():
            return Response({'error': '已达到抽奖上限'}, status=status.HTTP_400_BAD_REQUEST)
        if customizeactivity.is_draw_code == 1:
            redis_conn = get_redis_connection("default")
            prize_draw = redis_conn.get("prize_draw_%s" % user.id)
            if prize_draw:
                return Response({'error': '输入兑奖码错误3次,请等待10分钟再操作'}, status=status.HTTP_400_BAD_REQUEST)
            if not draw_code:
                return Response({'error': '请输入兑奖码'}, status=status.HTTP_400_BAD_REQUEST)
            customizeactivityprizedrawcode_set = CustomizeActivityPrizeDrawCode.objects.filter(draw_code=draw_code, customizeactivity_id=customizeactivity.id)
            if not customizeactivityprizedrawcode_set:
                prize_draw_count = redis_conn.get("prize_draw_count_%s" % user.id)
                if prize_draw_count:
                    prize_draw_count = int(prize_draw_count.decode()) + 1
                else:
                    prize_draw_count = 1
                if prize_draw_count >= 3:
                    cut_off_time = (datetime.datetime.now() + datetime.timedelta(minutes=10)).strftime('%Y/%m/%d %H:%M:%S')
                    redis_conn.setex("prize_draw_%s" % user.id, 570, cut_off_time)
                redis_conn.setex("prize_draw_count_%s" % user.id, 570, str(prize_draw_count))
                return Response({'error': '无效兑奖码'}, status=status.HTTP_400_BAD_REQUEST)
            customizeactivityprizedrawcode = customizeactivityprizedrawcode_set.filter(customeruser_id__isnull=True, customeruservice_id__isnull=True).first()
            if not customizeactivityprizedrawcode:
                return Response({'error': '兑奖码已兑完'}, status=status.HTTP_400_BAD_REQUEST)
            customizeactivityprizedrawcode.customeruser_id = user.id
            customizeactivityprizedrawcode.save()
        check_customizeactivityrules_set = customizeactivity.customizeactivityrules_set.filter(Q(alidiscountcoupon__remain_number__gt=0) | Q(cashactivity__remain_amount__gt=0) | Q(prize_type=4))
        if not check_customizeactivityrules_set:
            data = {}
            data["id"] = 'X'
            identify = f'{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}{"%06d" % randint(0, 999999)}{"%06d" % user.id}'
            instance_data = dict()
            instance_data['identify'] = identify
            instance_data['user_id'] = user.id
            instance_data['mobile'] = user.mobile
            instance_data['gears'] = 1
            instance_data['customizeactivity_id'] = customizeactivity.id
            instance_data['level_id'] = level.id
            instance_data['open_status'] = 3
            instance_data['open_time'] = datetime.datetime.now()
            instance = CustomizeActivityFlipCARDS.objects.create(**instance_data)
            if customizeactivity.is_business_form == 1:
                try:
                    business_form_data = {}
                    business_form_data['business_name'] = business_name
                    business_form_data['business_account'] = business_account
                    business_form_data['business_amount'] = business_amount
                    business_form_data['business_type'] = business_type
                    business_form_data['customizeactivityflipcards_id'] = instance.id
                    CustomizeActivityBusinessForm.objects.create(**business_form_data)
                except:
                    pass
            data["take_id"] = instance.id
            data["amount"] = ''
            data["activity_name"] = ''
            data["msg"] = ''
            data["available_time"] = ''
            data["win_type_str"] = '谢谢参与'
            data["win_type"] = 4
            if customizeactivity.is_draw_code == 1:
                try:
                    customizeactivityprizedrawcode.customizeactivityflipcards_id = instance.id
                    customizeactivityprizedrawcode.save()
                except:
                    pass
            return Response({'success': '谢谢参与', 'data': data}, status=status.HTTP_200_OK)
        else:
            list_data = []
            for check_customizeactivityrules in check_customizeactivityrules_set:
                probability = int(check_customizeactivityrules.count)
                for i in range(probability):
                    list_data.append(check_customizeactivityrules.id)
            if list_data:
                if customizeactivity.is_draw_code == 1:
                    if customizeactivityprizedrawcode.customizeactivityrules_id:
                        customizeactivityrules_id = customizeactivityprizedrawcode.customizeactivityrules_id
                    else:
                        customizeactivityrules_id = random.choices(list_data, k=1)[0]
                else:
                    customizeactivityrules_id = random.choices(list_data, k=1)[0]
            else:
                customizeactivityrules_id = check_customizeactivityrules_set.filter(prize_type=4).first().id
            customizeactivityrules = CustomizeActivityRules.objects.get(id=customizeactivityrules_id)
            identify = f'{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}{"%06d" % randint(0, 999999)}{"%06d" % user.id}'
            instance_data = dict()
            instance_data['identify'] = identify
            instance_data['user_id'] = user.id
            instance_data['mobile'] = user.mobile
            instance_data['gears'] = 1
            instance_data['customizeactivity_id'] = customizeactivity.id
            instance_data['level_id'] = level.id
            if customizeactivityrules.prize_type in [1, 2, 7]:
                instance_data['alidiscountcoupon_id'] = customizeactivityrules.alidiscountcoupon_id
                instance_data['win_type'] = customizeactivityrules.prize_type
            elif customizeactivityrules.prize_type in [3, 6]:
                instance_data['cashactivity_id'] = customizeactivityrules.cashactivity_id
                instance_data['win_type'] = customizeactivityrules.prize_type
            instance = CustomizeActivityFlipCARDS.objects.create(**instance_data)
            if customizeactivity.is_business_form == 1:
                try:
                    business_form_data = {}
                    business_form_data['business_name'] = business_name
                    business_form_data['business_account'] = business_account
                    business_form_data['business_amount'] = business_amount
                    business_form_data['business_type'] = business_type
                    business_form_data['customizeactivityflipcards_id'] = instance.id
                    CustomizeActivityBusinessForm.objects.create(**business_form_data)
                except:
                    pass
            if instance.win_type == 4:
                instance.open_status = 3
                instance.open_time = datetime.datetime.now()
                instance.save()
                data = {}
                data['id'] = customizeactivityrules_id
                data['take_id'] = instance.id
                data["amount"] = ''
                data["activity_name"] = ''
                data["msg"] = ''
                data["available_time"] = ''
                data["win_type_str"] = '谢谢参与'
                data["win_type"] = 4
                if customizeactivity.is_draw_code == 1:
                    try:
                        customizeactivityprizedrawcode.customizeactivityflipcards_id = instance.id
                        customizeactivityprizedrawcode.save()
                    except:
                        pass
                return Response({'success': '谢谢参与', 'data': data},status=status.HTTP_200_OK)
            elif instance.win_type in [1, 2, 7]:
                instance.open_status = 2
                instance.open_time = datetime.datetime.now()
                instance.save()
                alidiscountcoupon = instance.alidiscountcoupon
                data = {}
                if alidiscountcoupon.remain_number <= 0:
                    x = list(customizeactivity.customizeactivityrules_set.filter(alidiscountcoupon__remain_number__gt=0).values_list('alidiscountcoupon_id', flat=True))
                    if x:
                        shuffle(x)
                        alidiscountcoupon = AliDiscountCoupon.objects.get(id=x[0])
                        instance.alidiscountcoupon_id = alidiscountcoupon.id
                        instance.save()
                    else:
                        instance.open_status = 3
                        instance.win_type = 4
                        instance.open_time = datetime.datetime.now()
                        instance.save()
                        data['id'] = customizeactivityrules_id
                        data['take_id'] = instance.id
                        data["amount"] = ''
                        data["activity_name"] = ''
                        data["msg"] = ''
                        data["available_time"] = ''
                        data["win_type_str"] = '谢谢参与'
                        data["win_type"] = 4
                        if customizeactivity.is_draw_code == 1:
                            try:
                                customizeactivityprizedrawcode.customizeactivityflipcards_id = instance.id
                                customizeactivityprizedrawcode.save()
                            except:
                                pass
                        return Response({'success': '谢谢参与', 'data': data}, status=status.HTTP_200_OK)
                activity_id = alidiscountcoupon.id
                while True:
                    alidiscountcoupon = AliDiscountCoupon.objects.get(id=activity_id)
                    activity_origin_send_count = alidiscountcoupon.send_count
                    activity_origin_remain_number = alidiscountcoupon.remain_number
                    activity_new_send_count = activity_origin_send_count + 1
                    activity_new_remain_number = activity_origin_remain_number - 1
                    if activity_new_remain_number < 0:
                        instance.open_status = 3
                        instance.win_type = 4
                        instance.open_time = datetime.datetime.now()
                        instance.save()
                        data['id'] = customizeactivityrules_id
                        data['take_id'] = instance.id
                        data["amount"] = ''
                        data["activity_name"] = ''
                        data["msg"] = ''
                        data["available_time"] = ''
                        data["win_type_str"] = '谢谢参与'
                        data["win_type"] = 4
                        if customizeactivity.is_draw_code == 1:
                            try:
                                customizeactivityprizedrawcode.customizeactivityflipcards_id = instance.id
                                customizeactivityprizedrawcode.save()
                            except:
                                pass
                        return Response({'success': '谢谢参与', 'data': data}, status=status.HTTP_200_OK)
                    result = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(send_count=activity_new_send_count, remain_number=activity_new_remain_number)
                    if result == 0:
                        continue
                    break
                alidiscountcouponinfo_data = {}
                alidiscountcouponinfo_data['alidiscountcoupon_id'] = alidiscountcoupon.id
                alidiscountcouponinfo_data['level_id'] = instance.level_id
                alidiscountcouponinfo_data['status'] = 0
                alidiscountcouponinfo_data['template_id'] = alidiscountcoupon.template_id
                out_biz_no = f'{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}{"%06d" % randint(0, 999999)}{"%06d" % user.id}'
                alidiscountcouponinfo_data['out_biz_no'] = out_biz_no
                alidiscountcouponinfo_data['mobile'] = user.mobile
                alidiscountcouponinfo_data['gmt_distributed'] = datetime.datetime.now()
                alidiscountcouponinfo_data['customer_user_id'] = user.id
                alidiscountcouponinfo_data['coupon_channel'] = alidiscountcoupon.coupon_channel
                alidiscountcouponinfo, crete = AliDiscountCouponInfo.objects.get_or_create(defaults=alidiscountcouponinfo_data, out_biz_no=out_biz_no)
                instance.alidiscountcouponinfo_id = alidiscountcouponinfo.id
                instance.save()
                data['id'] = customizeactivityrules_id
                data['take_id'] = instance.id
                if alidiscountcoupon.coupon_type == 6:
                    data["amount"] = '单品券'
                else:
                    data["amount"] = alidiscountcoupon.amount
                data["activity_name"] = alidiscountcoupon.activity_name
                data["msg"] = alidiscountcoupon.floor_amount
                data["available_time"] = f'{alidiscountcoupon.publish_start_time.strftime("%Y.%m.%d %H:%M:%S")}-{alidiscountcoupon.publish_end_time.strftime("%Y.%m.%d %H:%M:%S")}'
                data["win_type_str"] = instance.get_win_type_display()
                data["win_type"] = instance.win_type
                data["coupon_type"] = alidiscountcoupon.coupon_type
                if customizeactivity.is_draw_code == 1:
                    try:
                        customizeactivityprizedrawcode.customizeactivityflipcards_id = instance.id
                        customizeactivityprizedrawcode.save()
                    except:
                        pass
                return Response({'success': '恭喜你中奖了', 'data': data}, status=status.HTTP_200_OK)
            else:
                data = {}
                instance.open_status = 2
                instance.open_time = datetime.datetime.now()
                instance.save()
                cashactivity = instance.cashactivity
                cashactivityrule = CashActivityRule.objects.filter(cash_activity_id=cashactivity.id, is_delete=0).first()
                if cashactivityrule.amount > cashactivity.remain_amount:
                    instance.open_status = 3
                    instance.win_type = 4
                    instance.open_time = datetime.datetime.now()
                    instance.save()
                    data['id'] = customizeactivityrules_id
                    data['take_id'] = instance.id
                    data["amount"] = ''
                    data["activity_name"] = ''
                    data["msg"] = ''
                    data["available_time"] = ''
                    data["win_type_str"] = '谢谢参与'
                    data["win_type"] = 4
                    if customizeactivity.is_draw_code == 1:
                        try:
                            customizeactivityprizedrawcode.customizeactivityflipcards_id = instance.id
                            customizeactivityprizedrawcode.save()
                        except:
                            pass
                    return Response({'success': '谢谢参与', 'data': data}, status=status.HTTP_200_OK)
                amount = cashactivityrule.amount
                activity_id = cashactivity.id
                while True:
                    activity = CashActivity.objects.get(id=activity_id)
                    activity_origin_take_amount = activity.take_amount
                    activity_origin_remain_amount = activity.remain_amount
                    if activity_origin_remain_amount < amount:
                        instance.open_status = 3
                        instance.win_type = 4
                        instance.open_time = datetime.datetime.now()
                        instance.save()
                        data['id'] = customizeactivityrules_id
                        data['take_id'] = instance.id
                        data["amount"] = ''
                        data["activity_name"] = ''
                        data["msg"] = ''
                        data["available_time"] = ''
                        data["win_type_str"] = '谢谢参与'
                        data["win_type"] = 4
                        if customizeactivity.is_draw_code == 1:
                            try:
                                customizeactivityprizedrawcode.customizeactivityflipcards_id = instance.id
                                customizeactivityprizedrawcode.save()
                            except:
                                pass
                        return Response({'success': '谢谢参与', 'data': data}, status=status.HTTP_200_OK)
                    activity_new_take_amount = activity_origin_take_amount + amount
                    activity_new_remain_amount = activity_origin_remain_amount - amount
                    result = CashActivity.objects.filter(take_amount=activity_origin_take_amount, remain_amount=activity_origin_remain_amount, id=activity_id).update(take_amount=activity_new_take_amount, remain_amount=activity_new_remain_amount)
                    if result == 0:
                        continue
                    break
                date_now = datetime.datetime.now()
                activity_data = {}
                activity_data['amount'] = amount
                activity_data['create_time'] = date_now
                activity_data['cash_activity_id'] = activity.id
                activity_data['level_id'] = instance.level_id
                activity_data['state'] = 1
                identify = random_str()
                nonce_str = random_str()
                activity_data['identify'] = identify
                activity_data['nonce_str'] = nonce_str
                activity_data['desc'] = activity.name
                activity_data['partner_trade_no'] = f'{date_now.strftime("%Y%m%d%H%M%S")}{"%06d" % randint(0, 999999)}{"%06d" % user.id}'
                activity_data['expired_time'] = date_now + datetime.timedelta(hours=11)
                activity_data['mobile'] = user.mobile
                activity_data['customer_user_id'] = user.id
                activity_dat, create = CashActivityData.objects.get_or_create(defaults=activity_data, identify=identify)
                instance.cashactivitydata_id = activity_dat.id
                instance.amount = amount
                instance.save()
                data['id'] = customizeactivityrules_id
                data['take_id'] = instance.id
                data["amount"] = amount
                data["activity_name"] = cashactivity.name
                data["msg"] = ''
                data["available_time"] = f'{cashactivity.available_begin_time.strftime("%Y.%m.%d %H:%M:%S")}-{cashactivity.available_end_time.strftime("%Y.%m.%d %H:%M:%S")}'
                data["win_type_str"] = instance.get_win_type_display()
                data["win_type"] = instance.win_type
                if customizeactivity.is_draw_code == 1:
                    try:
                        customizeactivityprizedrawcode.customizeactivityflipcards_id = instance.id
                        customizeactivityprizedrawcode.save()
                    except:
                        pass
                return Response({'success': '恭喜你中奖了', 'data': data}, status=status.HTTP_200_OK)

    def update(self, request, *args, **kwargs):
        user = self.request.iser
        instance = self.get_object()
        if instance.open_status != 1:
            return Response({'error': '礼包状态有误'}, status=status.HTTP_400_BAD_REQUEST)
        customizeactivity = instance.customizeactivity
        if user.is_auth != 2 and customizeactivity.is_need_auth == 1:
            return Response({'error': '请先完成实名认证', 'state': '0'}, status=status.HTTP_400_BAD_REQUEST)
        if customizeactivity.lucky_count_by_user <= CustomizeActivityFlipCARDS.objects.filter(user_id=user.id, customizeactivity=customizeactivity).exclude(open_status=1).count():
            return Response({'error': '已达到抽奖上限'}, status=status.HTTP_400_BAD_REQUEST)
        data = {}
        if instance.win_type != 4:
            instance.open_status = 2
            instance.open_time = datetime.datetime.now()
            instance.save()
            if instance.win_type in [3, 6]:
                cashactivity = instance.cashactivity
                cashactivityrule_set = CashActivityRule.objects.filter(cash_activity_id=cashactivity.id, is_delete=0)
                list_data = []
                for cashactivityrule in cashactivityrule_set:
                    if cashactivityrule.amount <= cashactivity.remain_amount:
                        probability = int(cashactivityrule.probability.quantize(Decimal("0")))
                        for i in range(probability):
                            list_data.append(cashactivityrule.amount)
                if not list_data:
                    instance.open_status = 3
                    instance.win_type = 4
                    instance.open_time = datetime.datetime.now()
                    instance.save()
                    data['amount'] = ''
                    data['msg'] = ''
                    data['win_type'] = 4
                    data['win_type_str'] = '谢谢参与'
                    return Response({'success': '谢谢参与', 'data': data}, status=status.HTTP_200_OK)
                amount = random.choices(list_data, k=1)[0]
                activity_id = cashactivity.id
                while True:
                    activity = CashActivity.objects.get(id=activity_id)
                    activity_origin_take_amount = activity.take_amount
                    activity_origin_remain_amount = activity.remain_amount
                    if activity_origin_remain_amount < amount:
                        instance.open_status = 3
                        instance.win_type = 4
                        instance.open_time = datetime.datetime.now()
                        instance.save()
                        data['amount'] = ''
                        data['msg'] = ''
                        data['win_type'] = 4
                        data['win_type_str'] = '谢谢参与'
                        return Response({'success': '谢谢参与', 'data': data}, status=status.HTTP_200_OK)
                    activity_new_take_amount = activity_origin_take_amount + amount
                    activity_new_remain_amount = activity_origin_remain_amount - amount
                    result = CashActivity.objects.filter(take_amount=activity_origin_take_amount, remain_amount=activity_origin_remain_amount, id=activity_id).update(take_amount=activity_new_take_amount, remain_amount=activity_new_remain_amount)
                    if result == 0:
                        continue
                    break
                date_now = datetime.datetime.now()
                activity_data = {}
                activity_data['amount'] = amount
                activity_data['create_time'] = date_now
                activity_data['cash_activity_id'] = activity.id
                activity_data['level_id'] = instance.level_id
                activity_data['state'] = 1
                identify = random_str()
                nonce_str = random_str()
                activity_data['identify'] = identify
                activity_data['nonce_str'] = nonce_str
                activity_data['desc'] = activity.name
                activity_data['partner_trade_no'] = f'{date_now.strftime("%Y%m%d%H%M%S")}{"%06d" % randint(0, 999999)}{"%06d" % user.id}'
                activity_data['expired_time'] = date_now + datetime.timedelta(hours=11)
                activity_data['mobile'] = user.mobile
                activity_data['customer_user_id'] = user.id
                activity_dat, create = CashActivityData.objects.get_or_create(defaults=activity_data, identify=identify)
                instance.cashactivitydata_id = activity_dat.id
                instance.amount = amount
                instance.save()
                data['amount'] = amount
                data['msg'] = ''
                data['win_type'] = instance.win_type
                data['win_type_str'] = instance.get_win_type_display()
            else:
                alidiscountcoupon = instance.alidiscountcoupon
                if alidiscountcoupon.remain_number <= 0:
                    # instance.open_status = 3
                    # instance.win_type = 4
                    # instance.open_time = datetime.datetime.now()
                    # instance.save()
                    # data['amount'] = ''
                    # data['msg'] = ''
                    # data['win_type'] = 4
                    # data['win_type_str'] = '谢谢参与'
                    # return Response({'success': '谢谢参与', 'data': data}, status=status.HTTP_200_OK)
                    x = list(customizeactivity.customizeactivityrules_set.filter(alidiscountcoupon__remain_number__gt=0).values_list('alidiscountcoupon_id', flat=True))
                    if x:
                        shuffle(x)
                        alidiscountcoupon = AliDiscountCoupon.objects.get(id=x[0])
                        instance.alidiscountcoupon_id = alidiscountcoupon.id
                        instance.save()
                    else:
                        instance.open_status = 3
                        instance.win_type = 4
                        instance.open_time = datetime.datetime.now()
                        instance.save()
                        data['amount'] = ''
                        data['msg'] = ''
                        data['win_type'] = 4
                        data['win_type_str'] = '谢谢参与'
                        return Response({'success': '谢谢参与', 'data': data}, status=status.HTTP_200_OK)
                activity_id = alidiscountcoupon.id
                while True:
                    alidiscountcoupon = AliDiscountCoupon.objects.get(id=activity_id)
                    activity_origin_send_count = alidiscountcoupon.send_count
                    activity_origin_remain_number = alidiscountcoupon.remain_number
                    activity_new_send_count = activity_origin_send_count + 1
                    activity_new_remain_number = activity_origin_remain_number -1
                    if activity_new_remain_number < 0:
                        instance.open_status = 3
                        instance.win_type = 4
                        instance.open_time = datetime.datetime.now()
                        instance.save()
                        data['amount'] = ''
                        data['msg'] = ''
                        data['win_type'] = 4
                        data['win_type_str'] = '谢谢参与'
                        return Response({'success': '谢谢参与', 'data': data}, status=status.HTTP_200_OK)
                    result = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
                        send_count=activity_new_send_count,
                        remain_number=activity_new_remain_number
                    )
                    if result == 0:
                        continue
                    break
                alidiscountcouponinfo_data = {}
                alidiscountcouponinfo_data['alidiscountcoupon_id'] = alidiscountcoupon.id
                alidiscountcouponinfo_data['level_id'] = instance.level_id
                alidiscountcouponinfo_data['status'] = 0
                alidiscountcouponinfo_data['template_id'] = alidiscountcoupon.template_id
                out_biz_no = f'{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}{"%06d" % randint(0, 999999)}{"%06d" % user.id}'
                alidiscountcouponinfo_data['out_biz_no'] = out_biz_no
                alidiscountcouponinfo_data['mobile'] = user.mobile
                alidiscountcouponinfo_data['gmt_distributed'] = datetime.datetime.now()
                alidiscountcouponinfo_data['customer_user_id'] = user.id
                alidiscountcouponinfo_data['coupon_channel'] = alidiscountcoupon.coupon_channel
                alidiscountcouponinfo, crete = AliDiscountCouponInfo.objects.get_or_create(defaults=alidiscountcouponinfo_data, out_biz_no=out_biz_no)
                instance.alidiscountcouponinfo_id = alidiscountcouponinfo.id
                instance.save()
                data['amount'] = alidiscountcoupon.amount
                data['activity_name'] = alidiscountcoupon.activity_name
                data['msg'] = alidiscountcoupon.floor_amount
                data['win_type'] = instance.win_type
                data['win_type_str'] = instance.get_win_type_display()
                data['id'] = instance.id
                data['available_time'] = f'{alidiscountcoupon.publish_start_time.strftime("%Y.%m.%d %H:%M:%S")}-{alidiscountcoupon.publish_end_time.strftime("%Y.%m.%d %H:%M:%S")}'
            return Response({'success': '恭喜你中奖了', 'data': data}, status=status.HTTP_200_OK)
        else:
            instance.open_status = 3
            instance.open_time = datetime.datetime.now()
            instance.save()
            data['amount'] = ''
            data['msg'] = ''
            data['win_type'] = 4
            data['win_type_str'] = '谢谢参与'
            data['activity_name'] = ''
            data['available_time'] = ''
            data['id'] = instance.id
            return Response({'success': '谢谢参与', 'data': data},status=status.HTTP_200_OK)

    def partial_update(self, request, *args, **kwargs):
        user = self.request.iser
        instance = self.get_object()
        if instance.open_status not in [2, 6]:
            return Response({'error': '礼包状态有误'}, status=status.HTTP_400_BAD_REQUEST)
        if instance.open_status == 6:
            if instance.win_type in [1, 2]:
                alidiscountcouponinfo = instance.alidiscountcouponinfo
                out_biz_no = f'{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}{"%06d" % randint(0, 999999)}{"%06d" % user.id}'
                alidiscountcouponinfo.out_biz_no = out_biz_no
                alidiscountcouponinfo.save()
            elif instance.win_type in [3, 6]:
                cashactivitydata = instance.cashactivitydata
                partner_trade_no = f'{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}{"%06d" % randint(0, 999999)}{"%06d" % user.id}'
                cashactivitydata.partner_trade_no = partner_trade_no
                cashactivitydata.save()
            else:
                return Response({'error': '奖品类型有误'}, status=status.HTTP_400_BAD_REQUEST)
        login_id = self.request.data.get('login_id', None)
        realname = self.request.data.get('realname', None)
        if instance.win_type == 1:
            if not login_id:
                return Response({'error': '请上传领取账户'}, status=status.HTTP_400_BAD_REQUEST)
            alidiscountcouponinfo = instance.alidiscountcouponinfo
            alidiscountcoupon = alidiscountcouponinfo.alidiscountcoupon
            out_biz_no = alidiscountcouponinfo.out_biz_no
            alipay_obj = AlipayOpen()
            template_id = alidiscountcoupon.template_id
            result = json.loads(alipay_obj.vouchersend_login_id(login_id, template_id, out_biz_no))
            if result['code'] != '10000':
                logger.error(str(result))
                instance.received_time = datetime.datetime.now()
                instance.open_status = 6
                instance.save()
                try:
                    instance.return_msg = result['sub_msg']
                    instance.save()
                    return Response({'error': result['sub_msg']}, status=status.HTTP_400_BAD_REQUEST)
                except:
                    return Response({'error': '领取失败,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
            voucher_id = result['voucher_id']
            voucherinfo = AliDiscountCouponInfo.objects.filter(voucher_id=voucher_id).first()
            if voucherinfo:
                instance.received_time = datetime.datetime.now()
                instance.open_status = 4
                instance.save()
                return Response({'success': '领取成功', 'status': ''}, status=status.HTTP_200_OK)
            if alidiscountcoupon.platform_id == 1:
                result = json.loads(alipay_obj.voucherquery(voucher_id))
                alidiscountcouponinfo.voucher_id = voucher_id
                alidiscountcouponinfo.login_id = login_id
                alidiscountcouponinfo.template_id = result['template_id']
                alidiscountcouponinfo.gmt_active = result['gmt_active']
                alidiscountcouponinfo.gmt_expired = result['gmt_expired']
                alidiscountcouponinfo.total_amount = result['total_amount']
                alidiscountcouponinfo.gmt_create = result['gmt_create']
                alidiscountcouponinfo.available_amount = result['available_amount']
                alidiscountcouponinfo.name = result['name']
                alidiscountcouponinfo.status = 1
                alidiscountcouponinfo.save()
            else:
                gmt_create = datetime.datetime.now()
                alidiscountcouponchannelcommonvoucher = alidiscountcoupon.alidiscountcouponchannelcommonvoucher
                if alidiscountcouponchannelcommonvoucher.usetime_type == 2:
                    gmt_expired = alidiscountcouponchannelcommonvoucher.end_fixed_time
                    gmt_active = alidiscountcouponchannelcommonvoucher.start_fixed_time
                elif alidiscountcouponchannelcommonvoucher.usetime_type == 3:
                    gmt_expired = gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)
                    gmt_active = gmt_create
                else:
                    gmt_active = (gmt_create + datetime.timedelta(days=1)).strftime("%Y-%m-%d 00:00:00")
                    gmt_expired = (gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)).strftime("%Y-%m-%d 23:59:59")
                alidiscountcouponinfo.voucher_id = voucher_id
                alidiscountcouponinfo.login_id = login_id
                alidiscountcouponinfo.template_id = alidiscountcoupon.template_id
                alidiscountcouponinfo.gmt_active = gmt_active
                alidiscountcouponinfo.gmt_expired = gmt_expired
                alidiscountcouponinfo.total_amount = alidiscountcoupon.amount
                alidiscountcouponinfo.gmt_create = gmt_create
                alidiscountcouponinfo.available_amount = alidiscountcoupon.amount
                alidiscountcouponinfo.name = alidiscountcoupon.activity_name
                alidiscountcouponinfo.status = 1
                alidiscountcouponinfo.save()
            instance.received_time = datetime.datetime.now()
            instance.open_status = 4
            instance.save()
            return Response({'success': '领取成功', 'status': ''}, status=status.HTTP_200_OK)
        elif instance.win_type == 2:
            alidiscountcouponinfo = instance.alidiscountcouponinfo
            alidiscountcoupon = alidiscountcouponinfo.alidiscountcoupon
            if user.new_openid:
                appid = settings.CUSTOMER_APP_ID_NEW
                openid = user.new_openid
            elif user.openid:
                appid = settings.CUSTOMER_APP_ID
                openid = user.openid
            else:
                return Response({'error': '用户尚未关联微信,请使用微信【赋有】小程序授权登录'}, status=status.HTTP_400_BAD_REQUEST)
            if alidiscountcoupon.platform_id == 13:
                distribute_channel = Channel.objects.get(id=13)
            else:
                distribute_channel = Channel.objects.get(id=9)
            data_json = {
                "stock_id": alidiscountcoupon.template_id,
                "out_request_no": alidiscountcouponinfo.out_biz_no,
                "appid": appid,
                "stock_creator_mchid": alidiscountcoupon.platform.mchid
            }
            data_dict = favor_distributed_coupons_sichun(data_json, openid, distribute_channel)
            if 'code' in data_dict:
                instance.received_time = datetime.datetime.now()
                instance.open_status = 6
                instance.return_msg = data_dict['message']
                instance.save()
                return Response({'error': data_dict['message']}, status=status.HTTP_400_BAD_REQUEST)
            coupon_id = data_dict['coupon_id']
            voucherinfo = AliDiscountCouponInfo.objects.filter(voucher_id=coupon_id).first()
            if voucherinfo:
                return Response({'error': '已经领取过了'}, status=status.HTTP_400_BAD_REQUEST)
            result = favor_query_coupons_sichun(coupon_id, openid, appid, distribute_channel)
            alidiscountcouponinfo.voucher_id = coupon_id
            alidiscountcouponinfo.user_id = openid
            alidiscountcouponinfo.template_id = result['stock_id']
            alidiscountcouponinfo.gmt_active = result['available_begin_time'].replace('T', ' ').replace('+08:00', '')
            alidiscountcouponinfo.gmt_expired = result['available_end_time'].replace('T', ' ').replace('+08:00', '')
            alidiscountcouponinfo.total_amount = result['normal_coupon_information']['coupon_amount']/100
            alidiscountcouponinfo.gmt_create = datetime.datetime.now()
            alidiscountcouponinfo.available_amount = result['normal_coupon_information']['coupon_amount']/100
            alidiscountcouponinfo.name = result['coupon_name']
            alidiscountcouponinfo.status = 1
            alidiscountcouponinfo.appid = appid
            alidiscountcouponinfo.save()
            instance.received_time = datetime.datetime.now()
            instance.open_status = 4
            instance.save()
            return Response({'success': '领取成功', 'status': ''}, status=status.HTTP_200_OK)
        elif instance.win_type == 3:
            date_now = datetime.datetime.now()
            cashactivitydata = instance.cashactivitydata
            cash_activity_id = instance.cashactivity_id
            cashactivity = instance.cashactivity
            if user.new_openid:
                appid = settings.CUSTOMER_APP_ID_NEW
                openid = user.new_openid
            elif user.openid:
                appid = settings.CUSTOMER_APP_ID
                openid = user.openid
            else:
                return Response({'error': '用户尚未关联微信,请使用微信【邮惠权益】小程序授权登录', 'status': ''}, status=status.HTTP_400_BAD_REQUEST)
            today_time_begin = datetime.datetime.now().strftime('%Y-%m-%d 00:00:00')
            today_time_end = datetime.datetime.now().strftime('%Y-%m-%d 23:59:59')
            encouragedraw = CashActivityData.objects.filter(received_time__gte=today_time_begin, received_time__lte=today_time_end, return_msg__contains='已达到今日商户付款额度上限')
            if encouragedraw:
                return Response({'error': '微信额度已达到今日上限,请使用支付宝APP扫码领取', 'status': ''}, status=status.HTTP_400_BAD_REQUEST)
            encouragedraw_set = CashActivityData.objects.filter(received_time__gte=today_time_begin, received_time__lte=today_time_end, customer_user_id=user.id, state=2)
            today_amount = Decimal('0')
            for encouragedraw in encouragedraw_set:
                today_amount += encouragedraw.amount
            today_amount += cashactivitydata.amount
            if today_amount > Decimal('200'):
                return Response({'error': '微信额度已达到今日上限,请使用支付宝APP扫码领取', 'status': ''}, status=status.HTTP_400_BAD_REQUEST)
            else:
                cashactivitydata.state = 5
                cashactivitydata.channel_id = cashactivity.wx_channel_id
                cashactivitydata.save()
                mchid = '1486198522'
                params = {
                    'mch_appid': appid,
                    'mchid': '1486198522',  # 商户号
                    'nonce_str': cashactivitydata.nonce_str,
                    'partner_trade_no': cashactivitydata.partner_trade_no,
                    'openid': openid,
                    'check_name': 'NO_CHECK',
                    'amount': int(cashactivitydata.amount * 100),
                    'desc': cashactivitydata.desc
                }
                data_dict = mmpaymkttransfers(params)
            if data_dict['result_code'] == 'SUCCESS':
                cashactivitydata.state = 2
                cashactivitydata.received_time = data_dict['payment_time']
                cashactivitydata.payment_no = data_dict['payment_no']
                cashactivitydata.customer_user_id = user.id
                cashactivitydata.mchid = mchid
                cashactivitydata.save()
                instance.received_time = datetime.datetime.now()
                instance.open_status = 4
                instance.save()
                while True:
                    activity = CashActivity.objects.get(id=cash_activity_id)
                    origin_distributed_amount = activity.distributed_amount
                    new_distributed_amount = origin_distributed_amount + cashactivitydata.amount
                    result = CashActivity.objects.filter(id=cash_activity_id, distributed_amount=origin_distributed_amount).update(distributed_amount=new_distributed_amount)
                    if result == 0:
                        continue
                    break
                return Response({'success': '领取成功', 'status': ''}, status=status.HTTP_200_OK)
            else:
                cashactivitydata.return_msg = data_dict['err_code_des']
                cashactivitydata.state = 3
                cashactivitydata.received_time = date_now
                cashactivitydata.customer_user_id = user.id
                cashactivitydata.mchid = mchid
                cashactivitydata.save()
                instance.received_time = datetime.datetime.now()
                instance.open_status = 6
                instance.return_msg = data_dict['err_code_des']
                instance.save()
                return Response({'error': f'领取失败,{data_dict["err_code_des"]}', 'status': ''}, status=status.HTTP_400_BAD_REQUEST)
        elif instance.win_type == 6:
            date_now = datetime.datetime.now()
            cashactivitydata = instance.cashactivitydata
            cash_activity_id = instance.cashactivity_id
            cashactivity = instance.cashactivity
            if not login_id:
                return Response({'error': '请上传领取支付宝账号'}, status=status.HTTP_400_BAD_REQUEST)
            if not realname:
                return Response({'error': '请上传领取支付宝账号实名姓名'}, status=status.HTTP_400_BAD_REQUEST)
            cashactivitydata.state = 5
            cashactivitydata.channel_id = cashactivity.ali_channel_id
            cashactivitydata.save()
            alipay_obj = AlipayOpen()
            trans_amount = str(cashactivitydata.amount)
            order_title = cashactivitydata.desc
            out_biz_no = cashactivitydata.partner_trade_no
            identity = login_id
            if cashactivity.ali_channel_id == 8:
                result = json.loads(alipay_obj.transunitransfer_login_id_jiangxi88(identity, realname, out_biz_no, trans_amount, order_title))
            elif cashactivity.ali_channel_id == 11:
                result = json.loads(alipay_obj.transunitransfer_login_id_jiangxi88_jizhangben(identity, realname, out_biz_no, trans_amount, order_title))
            else:
                result = json.loads(alipay_obj.transunitransfer_login_id(identity, realname, out_biz_no, trans_amount, order_title))
            if result['code'] != '10000':
                cashactivitydata.return_msg = result['sub_msg']
                cashactivitydata.state = 3
                cashactivitydata.received_time = date_now
                cashactivitydata.customer_user_id = user.id
                cashactivitydata.login_id = login_id
                cashactivitydata.realname = realname
                cashactivitydata.mchid = 'alipay'
                cashactivitydata.save()
                instance.received_time = datetime.datetime.now()
                instance.open_status = 6
                instance.return_msg = result["sub_msg"]
                instance.save()
                return Response({'error': f'领取失败{result["sub_msg"]}', 'status': ''}, status=status.HTTP_400_BAD_REQUEST)
            else:
                cashactivitydata.received_time = result['trans_date']
                cashactivitydata.payment_no = result['pay_fund_order_id']
                cashactivitydata.customer_user_id = user.id
                cashactivitydata.login_id = login_id
                cashactivitydata.realname = realname
                cashactivitydata.mchid = 'alipay'
                cashactivitydata.state = 2
                cashactivitydata.save()
                instance.received_time = datetime.datetime.now()
                instance.open_status = 4
                instance.save()
                while True:
                    activity = CashActivity.objects.get(id=cash_activity_id)
                    origin_distributed_amount = activity.distributed_amount
                    new_distributed_amount = origin_distributed_amount + cashactivitydata.amount
                    result = CashActivity.objects.filter(id=cash_activity_id, distributed_amount=origin_distributed_amount).update(distributed_amount=new_distributed_amount)
                    if result == 0:
                        continue
                    break
                try:
                    eta = datetime.datetime.utcnow() + datetime.timedelta(seconds=10)
                    capture_payeeFullName.apply_async(({"activityqrcode_id": cashactivitydata.id},), eta=eta)
                except:
                    pass
                return Response({'success': '领取成功', 'status': ''}, status=status.HTTP_200_OK)
        elif instance.win_type == 7:
            voucher_id = f'{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}{random_str(14)}'
            alidiscountcouponinfo = instance.alidiscountcouponinfo
            alidiscountcoupon = alidiscountcouponinfo.alidiscountcoupon
            if user.new_openid:
                appid = settings.CUSTOMER_APP_ID_NEW
                openid = user.new_openid
            else:
                appid = settings.CUSTOMER_APP_ID
                openid = user.openid
            gmt_create = datetime.datetime.now()
            alidiscountcouponchannelcommonvoucher = alidiscountcoupon.alidiscountcouponchannelcommonvoucher
            if alidiscountcouponchannelcommonvoucher.usetime_type == 2:
                gmt_expired = alidiscountcouponchannelcommonvoucher.end_fixed_time
                gmt_active = alidiscountcouponchannelcommonvoucher.start_fixed_time
            elif alidiscountcouponchannelcommonvoucher.usetime_type == 3:
                gmt_expired = gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)
                gmt_active = gmt_create
            else:
                gmt_active = (gmt_create + datetime.timedelta(days=1)).strftime("%Y-%m-%d 00:00:00")
                gmt_expired = (gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)).strftime("%Y-%m-%d 23:59:59")
            alidiscountcouponinfo.voucher_id = voucher_id
            alidiscountcouponinfo.user_id = openid
            alidiscountcouponinfo.template_id = alidiscountcoupon.template_id
            alidiscountcouponinfo.gmt_active = gmt_active
            alidiscountcouponinfo.gmt_expired = gmt_expired
            alidiscountcouponinfo.total_amount = alidiscountcoupon.amount
            alidiscountcouponinfo.gmt_create = gmt_create
            alidiscountcouponinfo.available_amount = alidiscountcoupon.amount
            alidiscountcouponinfo.name = alidiscountcoupon.activity_name
            alidiscountcouponinfo.status = 1
            alidiscountcouponinfo.appid = appid
            alidiscountcouponinfo.save()
            instance.received_time = datetime.datetime.now()
            instance.open_status = 4
            instance.save()
            return Response({'success': '领取成功', 'status': '', 'alidiscountcoupon_id': alidiscountcoupon.id}, status=status.HTTP_200_OK)
        else:
            return Response({'error': '奖品类型有误'}, status=status.HTTP_400_BAD_REQUEST)

    def allow_couponbag(self, request):
        identify = self.request.query_params.get('identify', None)
        if not all([identify]):
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            qrcode = CustomizeActivityQRCode.objects.get(identify=identify)
        except:
            return Response({'error': '无效二维码,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
        customizeactivity_level = qrcode.customizeactivity_level
        customizeactivity = customizeactivity_level.customizeactivity
        data = {}
        data['activity_name'] = customizeactivity.activity_name
        data['publish_end_time'] = customizeactivity.available_end_time.strftime('%Y年%m月%d日 %H:%M:%S')
        data['activity_description'] = customizeactivity.activity_description
        data['qrcode_state'] = qrcode.qrcode_state
        data['is_need_auth'] = customizeactivity.is_need_auth
        data['is_psbc_card'] = customizeactivity.is_psbc_card
        customizeactivityrules_set = CustomizeActivityRules.objects.filter(customizeactivity_id=customizeactivity.id)
        coupon_data = []
        for customizeactivityrules in customizeactivityrules_set:
            rules_data = {}
            rules_data['floor_amount'] = customizeactivityrules.alidiscountcoupon.floor_amount
            rules_data['coupon_channel'] = customizeactivityrules.alidiscountcoupon.coupon_channel
            rules_data['count'] = customizeactivityrules.count
            coupon_data.append(rules_data)
        data['coupon_data'] = coupon_data
        return Response(data, status=status.HTTP_200_OK)

    def receive_couponbag(self, request):
        user = self.request.iser
        identify = self.request.data.get('identify', None)
        if not all([identify]):
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            qrcode = CustomizeActivityQRCode.objects.get(identify=identify)
        except:
            return Response({'error': '无效二维码,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
        if qrcode.qrcode_state != 1:
            return Response({'error': '二维码已被领取'}, status=status.HTTP_400_BAD_REQUEST)
        customizeactivity_level = qrcode.customizeactivity_level
        customizeactivity = customizeactivity_level.customizeactivity
        if customizeactivity_level.remain_number <= 0:
            return Response({'error': '活动额度已派完'}, status=status.HTTP_400_BAD_REQUEST)
        if customizeactivity.lucky_count_by_user:
            max_no = CustomizeActivityFlipCARDS.objects.filter(customizeactivity_id=customizeactivity.id, user_id=user.id).count()
            if max_no >= customizeactivity.lucky_count_by_user:
                return Response({'error': '用户参与活动次数已达上限，感谢您对本活动的支持！'}, status=status.HTTP_400_BAD_REQUEST)
        qrcode.qrcode_state = 2
        qrcode.save()
        with transaction.atomic():
            save_id = transaction.savepoint()
            try:
                customizeactivity_level_id = customizeactivity_level.id
                while True:
                    customizeactivity_level = CustomizeActivityLevel.objects.get(id=customizeactivity_level_id)
                    origin_take_number = customizeactivity_level.take_number
                    origin_remain_number = customizeactivity_level.remain_number
                    origin_receive_number = customizeactivity_level.receive_number
                    if origin_remain_number <= 0:
                        transaction.savepoint_rollback(save_id)
                        return Response({'error': '活动额度已派完'}, status=status.HTTP_400_BAD_REQUEST)
                    new_take_number = origin_take_number + 1
                    new_remain_number = origin_remain_number - 1
                    new_receive_number = origin_receive_number + 1
                    result = CustomizeActivityLevel.objects.filter(id=customizeactivity_level_id, take_number=origin_take_number, receive_number=origin_receive_number, remain_number=origin_remain_number).update(take_number=new_take_number, receive_number=new_receive_number, remain_number=new_remain_number)
                    if result == 0:
                        continue
                    break
                today = datetime.datetime.now()
                defaults = {}
                defaults['user_id'] = user.id
                defaults['open_status'] = 2
                defaults['identify'] = qrcode.out_biz_no
                defaults['received_time'] = today
                defaults['open_time'] = qrcode.gmt_distributed
                defaults['pay_time'] = today
                defaults['gears'] = 1
                defaults['win_type'] = 8
                defaults['customizeactivity_id'] = customizeactivity_level.customizeactivity_id
                defaults['level_id'] = qrcode.companyuser.level_id
                defaults['mobile'] = user.mobile
                defaults['companyuser_id'] = qrcode.companyuser_id
                instance, create = CustomizeActivityFlipCARDS.objects.get_or_create(defaults=defaults, identify=qrcode.out_biz_no)
            except:
                transaction.savepoint_rollback(save_id)
                return Response({'error': '领取失败,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
            transaction.savepoint_commit(save_id)
            distribute_couponbag.delay({"filp_id": instance.id})
            return Response({'success': '领取成功'}, status=status.HTTP_200_OK)


class CustomeruserBindCardOrderModelViewSet(ModelViewSet):

    def payment(self, request):
        user = self.request.iser
        if user.is_psbc_card == 1:
            return Response({'error': '重复验卡'}, status=status.HTTP_400_BAD_REQUEST)
        bindcardorder = CustomeruserBindCardOrder.objects.filter(customeruser_id=user.id, order_status=1).first()
        if not bindcardorder:
            out_trade_no = f'{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
            out_refund_no = f'{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
            bindcardorder_data = {}
            bindcardorder_data['customeruser_id'] = user.id
            bindcardorder_data['amount'] = 0.01
            bindcardorder_data['order_status'] = 1
            bindcardorder_data['description'] = '邮政一分钱验卡活动'
            bindcardorder_data['out_trade_no'] = out_trade_no
            bindcardorder_data['out_refund_no'] = out_refund_no
            bindcardorder, create = CustomeruserBindCardOrder.objects.get_or_create(defaults=bindcardorder_data, customeruser_id=user.id, order_status=1)
        openid = user.new_openid
        amount = 1
        appid = settings.CUSTOMER_APP_ID_NEW
        data_json = {}
        data_json['appid'] = appid
        data_json['mchid'] = '1486198522'
        data_json['description'] = bindcardorder.description
        data_json['out_trade_no'] = bindcardorder.out_trade_no
        data_json['notify_url'] = 'https://api.sutpay.com/cpay/customer_wxpay_result/'
        data_json['amount'] = {"total": amount}
        data_json['payer'] = {"openid": openid}
        data_dict = pay_transactions_jsapi(data_json, appid)
        # data_dict = pay_transactions_native(data_json)
        if 'code' in data_dict:
            if data_dict['code'] not in ['OUT_TRADE_NO_USED', 'ORDER_NOT_EXIST', 'ORDER_CLOSED', 'INVALID_REQUEST']:
                return Response({'error': data_dict['message']}, status=status.HTTP_400_BAD_REQUEST)
            else:
                out_trade_no = f'{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
                bindcardorder.out_trade_no = out_trade_no
                bindcardorder.save()
                data_json['out_trade_no'] = bindcardorder.out_trade_no
                data_dict = pay_transactions_jsapi(data_json, appid)
                if 'code' in data_dict:
                    return Response({'error': data_dict['message']}, status=status.HTTP_400_BAD_REQUEST)
        data_dict['out_trade_no'] = bindcardorder.out_trade_no
        return Response(data_dict, status=status.HTTP_200_OK)

    def check_order(self, request):
        user = self.request.iser
        out_trade_no = self.request.query_params.get('out_trade_no', None)
        if not out_trade_no:
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            bindcardorder = CustomeruserBindCardOrder.objects.get(customeruser_id=user.id, out_trade_no=out_trade_no)
        except:
            return Response({'error': '无效订单id'}, status=status.HTTP_400_BAD_REQUEST)
        if 'PSBC' in bindcardorder.bank_type:
            return Response({'success': '查询成功', 'status': 1}, status=status.HTTP_200_OK)
        else:
            return Response({'success': '查询成功', 'status': 0}, status=status.HTTP_200_OK)

